Vikas Singh
Vikas Singh

Reputation: 1791

How to send a basic POST HTTP request with a parameter and display the json response?

I tried a lot of things but somehow not able to figure the basics of an HTTP POST request in ios. Sometimes I get a server error other times I get status code 200 but an empty response. The backend server code works and it is sending json data in response. Somehow my ios app is not able to get that response. Any help will be appreciated!

This is one of the things I tried! GetAuthorOfBook corresponds to a php server function that accepts strBookName as a POST argument and returns the name of author as a json object!

NSURL *url = [NSURL URLWithString:@"http://mysite.com/getAuthorOfBook"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
NSString *post = [NSString stringWithFormat:@"strBookName=Rework"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];


[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
[request setValue:@"text/html" forHTTPHeaderField:@"Content-Type"];

[request setHTTPBody:postData ];

 //get response
 NSHTTPURLResponse* urlResponse = nil;  
 NSError *error = [[NSError alloc] init];

 NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

The responseData should have the name of the author(strAuthorName) as a json "key":"value" pair.

Upvotes: 0

Views: 877

Answers (1)

Brentoe
Brentoe

Reputation: 448

The responseData isn't a json object yet. First you need to serialise it and assign it to an NSDictionary, then you can parse it by key.

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];

Now you should be able to access authorName by either this method (if it is just a string in the json):

NSString *authorName = [json objectForKey:@"strAuthorName"];

or like this if it is a dictionary of objects (an array of objects in the json)

NSDictionary *authorName = [json objectForKey:@"strAuthorName"];

Upvotes: 1

Related Questions