Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending a JSON via POST in NSURLRequest

I have a problem with sending a JSON to a Server with REST API. This is the code i use:

NSString *jsonPostBody = [NSString stringWithFormat:@"'json' = '{\"user\":{\"username\":"
                          "\"%@\""
                          ",\"password\":"
                          "\"%@\""
                          "}}'",
                          [username stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
                          [password stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];       
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *apiPathParams = [NSString stringWithFormat:@"%@",
                           @"getUser"
                           ];

NSURL *url = [NSURL URLWithString:[[apiPath retain] stringByAppendingString:apiPathParams]];    
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url
                                                       cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
                                                   timeoutInterval:180.0];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:postData];
NSString* postDataLengthString = [[NSString alloc] initWithFormat:@"%d", [postData length]];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:postDataLengthString forHTTPHeaderField:@"Content-Length"];
[self internalRequest:request];

This is what the API would look like, if it was a html form:

<form method="post" action="someAPI-URL">
<input name="json" value="{"user":...}" />
</form>

This is what my POST Data looks like when i add it to the request:

json={"user":{"username":"someUser","password":"somePassword"}}

For a reason I don't know the POST Data does not arrive at the server. Have i done something wrong with the formatting of the dataString? How exactly must i format my dataString so that it matches the String a form as shown above would deliver to the server?

Any help would be highly appreciated.

P.S. I would rather not use ASIHttpRequest, since i took over the project from somebody else an every other request works fine, except this post-request. So changing this whole bulk to an other connection framework would be very time consuming.

Here is the internalRequest Method's sourcecode

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:req delegate:self];
NSMutableDictionary *di = [NSMutableDictionary dictionaryWithObject:[[NSMutableData alloc] init] forKey:@"receivedData"];   
[di setObject:[NSString stringWithFormat:@"%i",identifier] forKey:@"identifier"];
if (delegate == nil) 
{ 
    delegate = self;         
}
[di setObject:delegate forKey:@"delegate"];

CFDictionaryAddValue(connectionToInfoMapping, connection, di)
like image 211
Maverick1st Avatar asked Sep 13 '11 15:09

Maverick1st


People also ask

Can you send JSON in post?

To post JSON to a REST API endpoint, you must send an HTTP POST request to the REST API server and provide JSON data in the body of the POST message. You also need to specify the data type in the body of the POST message using the Content-Type: application/json request header.

How do I post JSON data?

To post JSON data to the server, we need to use the HTTP POST request method and set the correct MIME type for the body. The correct MIME type for JSON is application/json. In this POST JSON example, the Content-Type: application/json request header specifies the media type for the resource in the body.

How do I post a JSON payload?

To send the JSON with payload to the REST API endpoint, you need to enclose the JSON data in the body of the HTTP request and indicate the data type of the request body with the "Content-Type: application/json" request header.


1 Answers

since you try to submit a HTTP POST header like

json={"user":{"username":"%@","password":"%@"}},

this example is fully qualified to end up in confusion.

It's a mixture of application/x-www-form-urlencoded for the whole body and application/json for the value.

Maybe a way to resolve this:

You'll probably need to adjust that HTTP header:

 [request setValue:@"application/x-www-form-urlencoded" 
forHTTPHeaderField:@"Content-Type"];

due to an encoding of the JSON part (value) of the HTTP body:

[request setHTTPBody:[[jsonPostBody stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]
                      dataUsingEncoding:NSUTF8StringEncoding 
                   allowLossyConversion:YES]];    

where stringByAddingPercentEscapesUsingEncoding is objective c jabberwocky for the PHP equivalent urlencode.

HTH

like image 60
klaus Avatar answered Oct 01 '22 16:10

klaus