views:

1568

answers:

3

I implemented the following code:

NSURL *url = [ NSURL URLWithString:[ NSString stringWithFormat: @"http://www.google.com/search?q=%@", query ] ];
NSURLRequest *request = [ NSURLRequest requestWithURL: url ];

I want to extract the body from what I receive back from the url above. I attempted:

NSData *data = [request HTTPBody];

The data variable doesn't return any data? Am I going about extracting the data out of the request the right way?

Thanks!

+2  A: 

NSURLRequest just defines a request — it doesn't do anything by itself. To actually make a request, you need to give the request to an NSURLConnection.

Also, as indicated in the documentation, the HTTPBody is data that's sent with the request, not the response body.

Chuck
+1  A: 

If you're just trying to get a web page, you can use this.

NSURL *url = [ NSURL URLWithString: [ NSString stringWithFormat: @"http://www.google.com"] ]; 
NSString *test = [NSString stringWithContentsOfURL:url];

If you really want to convert the data from NSData you can use this:

NSString *myString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
Jordan
While not technically wrong per se, this code is probably ill advised. For an HTTP request, you almost certainly want to use the asynchronous API available through NSURLConnection.
Mike Abdullah
A: 

There is an article on www.eigo.co.uk which shows exactly how to do the request and get the response in a string variable but the chunk of code you need is...

NSString * strResult = [[NSString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];

Check out the article here http://www.eigo.co.uk/iPhone-Submitting-HTTP-Requests.aspx

Eigo