简体   繁体   中英

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
}

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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