tags:

views:

1458

answers:

2

Hi, can anyone paste some code on how to do a simple http get in cocoa?

+3  A: 

Take a look at NSURLConnection. You use it to request a URL, synchronously or (preferably) asynchronously. The full documentation for the URL system is here:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/URLLoadingSystem.html

But what you really probably want is:

http://developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html#//apple_ref/doc/uid/20001836-BAJEAIEE

Apple provides some sample code that should get you started.

Alex
+2  A: 

Here you go!

This one grabs an image from a webserver.

NSURL *url = [ NSURL URLWithString: [ NSString

stringWithFormat:@"http://www.somewebsite.com/demo.png"] ]; 
image = [ [ UIImage alloc ] initWithData: [ NSData dataWithContentsOfURL: url ] ];

or, this one grabs a web page...

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

To do it asynchronously, you should check out NSURLConnection.

Jordan
I do the second example populating the query variable with @"joe". I then do:NSData *responseData = [request HTTPBody ];and response data comes back with 0 bytes of info.Am I doing something wrong? I want to get the response and convert to string
Buffernet