POST请求响应400

时间:2017-04-28 01:11:35

标签: ios swift api http

我试图在我的应用中发送POST请求。但服务器响应400.我尝试使用string varientjson varient的解决方案。这两种情况我都得到错误代码400,但是如果我通过邮递员发送相同的请求它会响应200,并且正常工作。服务器API使用" http"我为它设置了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()
}

1 个答案:

答案 0 :(得分:1)

我建议您使用https://www.charlesproxy.com/之类的调试代理服务来查看请求是如何进行的。然后,您可以再次使用邮递员提出请求并进行比较,以便找到他们不同的地方。