Simple http post example in Objective-C? Simple http post example in Objective-C? ios ios

Simple http post example in Objective-C?


This is what I recently used, and it worked fine for me:

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.nowhere.com/sendFormHere.php"]];[request setHTTPMethod:@"POST"];[request setValue:postLength forHTTPHeaderField:@"Content-Length"];[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];[request setHTTPBody:postData];

Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.


From Apple's Official Website :

// In body data for the 'application/x-www-form-urlencoded' content type,// form fields are separated by an ampersand. Note the absence of a// leading ampersand.NSString *bodyData = @"name=Jane+Doe&address=123+Main+St";NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.apple.com"]];// Set the request's content type to application/x-www-form-urlencoded[postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];// Designate the request a POST request and specify its body data[postRequest setHTTPMethod:@"POST"];[postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];// Initialize the NSURLConnection and proceed as described in// Retrieving the Contents of a URL

From : code with chris

    // Create the request.NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"]];// Specify that it will be a POST requestrequest.HTTPMethod = @"POST";// This is how we set header fields[request setValue:@"application/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];// Convert your data and set your request's HTTPBody propertyNSString *stringData = @"some data";NSData *requestBodyData = [stringData dataUsingEncoding:NSUTF8StringEncoding];request.HTTPBody = requestBodyData;// Create url connection and fire requestNSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];


ASIHTTPRequest makes network communication really easy

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];[request addPostValue:@"Ben" forKey:@"names"];[request addPostValue:@"George" forKey:@"names"];[request addFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photos"];[request addData:imageData withFileName:@"george.jpg" andContentType:@"image/jpeg" forKey:@"photos"];