26

Is there a way using the iPhone SDK to get the same results as an HTTP POST or GET methods?

Chris Hanson
  • 54,380
  • 8
  • 73
  • 102

2 Answers2

44

Assume your class has a responseData instance variable, then:

responseData = [[NSMutableData data] retain];

NSURLRequest *request =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

And then add the following methods to your class:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // Show error
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // Once this method is invoked, "responseData" contains the complete result
}

This will send a GET. By the time the final method is called, responseData will contain the entire HTTP response (convert to string with [[NSString alloc] initWithData:encoding:].

Alternately, for POST, replace the first block of code with:

NSMutableURLRequest *request =
        [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://www.domain.com/path"]];
[request setHTTPMethod:@"POST"];

NSString *postString = @"Some post string";
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
Matt Gallagher
  • 14,858
  • 2
  • 41
  • 43
  • 1
    I posted a follow up question on this here: http://stackoverflow.com/questions/431826/making-get-and-post-requests-from-an-iphone-application-clarification-needed (I figured it was worthy of it's own question.) – Greg Jan 10 '09 at 22:23
  • Be sure to check that [[NSURLConnection alloc] initWithRequest:request delegate:self]; call for a nil return. – Erik Aug 31 '11 at 15:31
8

If you're using Objective C, you'll need to use the NSURL, NSURLRequest, and NURLConnection classes. Apple's NSURLRequest doc. HttpRequest is for JavaScript.

Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172