【问题标题】:POST request response 400POST 请求响应 400
【发布时间】:2017-09-25 23:47:49
【问题描述】:

我正在尝试在我的应用中发送 POST 请求。但是服务器响应 400。我尝试使用来自 string varientjson varient 的解决方案。这两种情况我都会收到错误代码 400,但如果我通过邮递员发送相同的请求,它会响应 200,并且可以正常工作。使用“http”的服务器 API,我为它设置了 plist 属性。

func requestSmsCode() {

    let postUrl = URL(string: "http://www.myServer.com/auth/send_phone")

    var request = URLRequest(url: postUrl!)
    request.httpMethod = "POST"
    let postString = "phone=myPhone"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(responseString)")
    }
    task.resume()
}


func requestSmsCodeWithJSON() {


    let json: [String: Any] = ["phone": "myPhone"]

    let jsonData = try? JSONSerialization.data(withJSONObject: json)

    let url = URL(string: "http://www.myServer.com/auth/send_phone")!
    var request = URLRequest(url: url)
    request.httpMethod = "POST"

    request.httpBody = jsonData

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print(error?.localizedDescription ?? "No data")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

        let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
        if let responseJSON = responseJSON as? [String: Any] {
            print(responseJSON)
        }
    }

    task.resume()
}

【问题讨论】:

  • 服务器端代码是什么样的?
  • @kichik 不幸的是,它对我来说是黑匣子。里面应该有问题吧?通过邮递员的请求以某种方式工作正常
  • 好吧,如果我们知道服务器期望什么,就更容易知道这段代码出了什么问题。如果 Postman 工作正常,那么查看它发送的确切请求会有所帮助。

标签: ios swift api http


【解决方案1】:

我建议您使用像https://www.charlesproxy.com/ 这样的调试代理服务来查看请求是如何发出的。然后你可以再次向邮递员提出请求并比较它们以找出它们的不同之处。

【讨论】:

  • 很好的建议。我知道我的帖子请求没有“postString”部分。如果我将“postString”保留为“”并将“phone=myPhone”粘贴到“postUrl”的末尾,则请求响应 200。它是如何工作的?
猜你喜欢
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-20
相关资源
最近更新 更多