我想用post方法设置“application/x-www-form-urlencoded”
所以,我设置了 request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
但是当我将请求设置为服务器的 Content-Type不改变会怎样?
这是错误
{com.alamofire.serialization.response.error.response=<NSHTTPURLResponse: 0x7c166450> { URL: http://test.com } { status code: 404, headers {
Connection = "keep-alive";
"Content-Length" = 434;
"Content-Type" = "text/html";
Date = "Mon, 13 Jul 2015 11:18:18 GMT";
Server = "nginx/1.0.15";
} }, NSErrorFailingURLKey=http://text.com, NSLocalizedDescription=Request failed: not found (404),
这是我的代码:
var request = AFHTTPRequestOperationManager();
request.requestSerializer = AFHTTPRequestSerializer()
request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.POST(url, parameters: parameters, success: { (oper,obj) -> Void in
// do something
}) { (oper, error) -> Void in
// do something with error
}
最佳答案
这正是错误所说的:当您期望 JSON 时,您的服务器正在发回 400 状态代码的网页 (HTML)。
400 状态代码用于错误请求,这可能是因为您将 URL 形式编码的文本作为 application/json 发送而生成的。您真正想要的是使用 AFJSONRequestSerializer 作为您的请求序列化程序。
manager.requestSerializer = [AFJSONRequestSerializer serializer];
我没有在 Swift 中编写 AFNetworking 的任何代码,所以我不能告诉你它的代码,但你可以从 objective-c 代码中了解。
希望对您有所帮助。
关于ios - 如何在 AFNetworking 中设置内容类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31382342/