5

I make http request to the web server with this:

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString: @"http://server.com"]]; 
[request setHTTPMethod: @"POST"];
[request setHTTPBody: myRequestData];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];

But how can I get the response from the server and parse it? Thanks a lot :)

Nevil Lad
  • 533
  • 6
  • 20
nyanev
  • 11,299
  • 6
  • 47
  • 76

3 Answers3

24

Since you're assigning response to returnData instance variable, convert it to string for starters just look what you get, the parsing may be done with either NSXMLParser or some JSON library depending on response format.

Here's how you'd convert the response to string:

NSString *responseBody = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
Eimantas
  • 48,927
  • 17
  • 132
  • 168
2

I assume you mean the full NSURLResponse so that you can inspect headers and the like. In which case you need to pass in the returningResponse parameter, it is an out parameter of type (NSURLResponse **). See the docs.

brain
  • 5,496
  • 1
  • 26
  • 29
  • I think he means the raw text returned by the server. The docs don't explain the difference between the NSURLResponse and the result, nor do they say how to get the response body from the NSURLResponse. – Oscar Dec 12 '12 at 22:56
2

returnData is your response. If its xml then you can use NSXMLParser to parse it, if its json use the JSONFramework.

Praveen S
  • 10,355
  • 2
  • 43
  • 69