Search code examples
iosswiftafnetworking

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?

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
}

Solution

  • 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.

    A 400 status code is used a bad request, which is probably generated because you're sending URL-form-encoded text as application/json. What you really want is to use AFJSONRequestSerializer for your request serializer.

    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.

    I hope it will help you.