我想用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
}
答案 0 :(得分:1)
这正是错误所说的:当您期待JSON时,您的服务器正在为400状态代码发回一个网页(HTML)。
400状态代码用于错误请求,这可能是因为您将URL格式编码的文本作为application / json发送而生成的。你真正想要的是将AFJSONRequestSerializer用于你的请求序列化器。
manager.requestSerializer = [AFJSONRequestSerializer serializer];
我没有在Swift中执行任何AFNetworking代码,所以我不能告诉你这些代码,但你可以从objective-c代码中获得想法。
我希望它会对你有所帮助。
答案 1 :(得分:0)
试试这个
let strURL = "Your URL"
let dictParam : NSDictionary = [
"u":"b",
"p":"1290",
]
let manager = AFHTTPSessionManager.init()
manager.requestSerializer.setValue("content-type", forHTTPHeaderField: "application/x-www-form-urlencoded")
manager.post(strURL, parameters: dictParam, progress: nil, success: { (task, responseObject) in
print(responseObject ?? "")
}, failure: { (task, error) in
print(error.localizedDescription)
})