Alamofire - 错误的请求
Alamofire - Bad request
我恐怕无法分享 API url。但我检查了 Postman,它有效。这是一个 POST 请求,以下是响应:
{
"user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}
邮差截图:
在代码中,这是我使用 Alamofire 发出的请求:
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseObject { (response: DataResponse<User>) in
let userResponse = response.result.value
print("")
}
但是 userResponse 变成了 nil。这是 User 对象:
import ObjectMapper
class User: Mappable {
var authToken: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.authToken <- map["user_key"]
}
}
我这里用的是ObjectMapper。
假设它不是 JSON
对象,我尝试将其作为 String
处理:
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseString { (response: DataResponse<String>) in
let dataUser = response.data as! Any
let dataUser1 = response.data as! AnyObject
let error = response.error
let code = response.response?.statusCode
print(response.value)
print(response.result.value)
}
仍然,没有。我无法检索该值。然而,状态代码是 400(错误请求)。
它到底是什么? JSON
对象还是 String
?我该如何解决这个问题?
尝试替换
这个 URLEncoding.httpBody
到 JSONEncoding.default
JSONEncoding.default
使用JSONSerialization
创建参数object的JSON表示,设置为请求的body。编码请求的 Content-Type
HTTP header 字段设置为 application/json
。
我恐怕无法分享 API url。但我检查了 Postman,它有效。这是一个 POST 请求,以下是响应:
{
"user_key": "b0aebdedb15e2beaaf479ca3c4f8227e8e970681"
}
邮差截图:
在代码中,这是我使用 Alamofire 发出的请求:
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseObject { (response: DataResponse<User>) in
let userResponse = response.result.value
print("")
}
但是 userResponse 变成了 nil。这是 User 对象:
import ObjectMapper
class User: Mappable {
var authToken: String?
required init?(map: Map) {
}
func mapping(map: Map) {
self.authToken <- map["user_key"]
}
}
我这里用的是ObjectMapper。
假设它不是 JSON
对象,我尝试将其作为 String
处理:
Alamofire.request("some url", method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: ["Content-Type":"application/json"])
.responseString { (response: DataResponse<String>) in
let dataUser = response.data as! Any
let dataUser1 = response.data as! AnyObject
let error = response.error
let code = response.response?.statusCode
print(response.value)
print(response.result.value)
}
仍然,没有。我无法检索该值。然而,状态代码是 400(错误请求)。
它到底是什么? JSON
对象还是 String
?我该如何解决这个问题?
尝试替换
这个 URLEncoding.httpBody
到 JSONEncoding.default
JSONEncoding.default
使用JSONSerialization
创建参数object的JSON表示,设置为请求的body。编码请求的 Content-Type
HTTP header 字段设置为 application/json
。