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!

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
Atma
  • 29,141
  • 56
  • 198
  • 299

3 Answers3

6

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
  • 21,746
  • 10
  • 51
  • 63
  • 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 Apr 01 '09 at 23:37
3

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
  • 234,037
  • 30
  • 302
  • 389
1

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

Martin Belcher - AtWrk
  • 4,579
  • 4
  • 33
  • 41