ios - 如何在 AFNetworking 中设置内容类型?

标签 ios swift afnetworking

我想用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/

相关文章:

ios - 当 MKMap 在 iOS 中面向北方时指南针消失

ios - 使用 CocoaPods 在 iOS 中安装 Google Analytics 时出错

Swift4 - Xcode 9 PCH 错误

ios - 表更新时 NSFetchedResultsController 无法滚动

swift - 在 Swift 中访问父类(super class)的私有(private)方法

ios - 设置缓存时间 AFNetworking swift 2

iphone - 按钮操作没有响应 iphone

ios - 如何在ios中找到用户点击屏幕的位置

ios - 需要帮助从 iOS 设备上传多个大图像

ios - AFJSONRequestOperation 不更新 block 外的内容