简体   繁体   English

如何在AFNetworking中设置Content-Type?

[英]How to set Content-Type in AFNetworking?

I want to set "application/x-www-form-urlencoded" with post method So ,I set request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") But When I set the request to the server the Content-Type is not change what happen? 我想用发布方法设置“ application / x-www-form-urlencoded”,所以,我设置了request.requestSerializer.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")但是当我将请求设置为服务器的Content-Type不更改会发生什么?

this is error 这是错误的

{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), 

this is my code: 这是我的代码:

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
}

It's exactly what the error says: your server is sending back a webpage (HTML) for a 400 status code, when you were expecting JSON. 错误的确切含义是:当您期望使用JSON时,您的服务器正在发送一个包含400状态代码的网页(HTML)。

A 400 status code is used a bad request, which is probably generated because you're sending URL-form-encoded text as application/json. 使用400状态代码表示错误的请求,这可能是由于您将URL形式编码的文本作为application / json发送而产生的。 What you really want is to use AFJSONRequestSerializer for your request serializer. 您真正想要的是对请求序列化程序使用AFJSONRequestSerializer。

manager.requestSerializer = [AFJSONRequestSerializer serializer];

I am not doing any code of AFNetworking in Swift so I can't tell you code of that but you can get idea from objective-c code. 我没有在Swift中执行AFNetworking的任何代码,所以我无法告诉您这些代码,但是您可以从Objective-C代码中获得启发。

I hope it will help you. 希望对您有帮助。

Try This 尝试这个

    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)
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM