Links: iPhone Dev Help Forums | Live Chat | iPhone OS Programming Guide | Apple Developer Site

Thursday, March 20, 2008

Useful Code: Retrieving a URL

I found that retrieving a URL (with a POST) in Cocoa is pretty simple. I'm sure someone will find this useful so I am posting the code to do it:


NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.someurl.com"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLConnection *conn=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (conn)
{
receivedData = [[NSMutableData data] retain];
}
else
{
// inform the user that the download could not be made
}


Check this thread out for more details:

Forums Thread

1 Comments:

At July 7, 2008 6:47 PM , Blogger Andrew Arrow said...

what if the value for key1 or key2 contains an "&"? How do you escape the string properly for an HTTP post?

 

Post a Comment

<< Home