【发布时间】:2017-09-25 23:47:49
【问题描述】:
我正在尝试在我的应用中发送 POST 请求。但是服务器响应 400。我尝试使用来自 string varient 和 json 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 工作正常,那么查看它发送的确切请求会有所帮助。