Question

I'm trying to port a curl request:

curl -X POST -H [header stuff]  -d '{"key":"value"}' [host] 

into a NSMutableUrlRequest. I've stripped out what's working fine so far, and only kept what's causing me troubles, namely -d '{"key":"value"}'. The other header part is fine.

According to curl manual -d means that the payload is sent in application/x-www-form-urlencoded format, so I did the following:

    NSString* post =   @"{\"key\":\"value\"}";
    NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
    [_request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [_request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    [_request setHTTPMethod:@"POST"];
    [_request setHTTPBody:postData];

This returns the following error

Failed with error Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0xa363550 {NSLocalizedRecoverySuggestion={"code":107,"error":"bad www-form-urlencoded data"}

Could any one point me in the right direction to debug this stuff ? -A

Was it helpful?

Solution

Content-Type should be application/json or maybe text/plain instead. If everything else fails, try application/octet-stream (raw binary data).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top