Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple http post example in Objective-C?

I have a php webpage that requires a login (userid & password). I have the user enter the information into the app just fine.. but I need an example on how to do a POST request to a website. The apple example on the support site is rather complicated showing a picture upload.. mine should be simpler.. I just want to post 2 lines of text.. Anyone have any good examples?

Alex

like image 454
Alex van Es Avatar asked Aug 25 '10 13:08

Alex van Es


People also ask

How do I send a post request in Objective C?

To make sure you don't have to set a params related to authentication or maybe the application/json. Just adding the parameters I wrote in (NSString post) to the URL is enough when using a browser. try NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];.

What is HTTP POST give an example?

HTTP works as a request-response protocol between a client and a server in a format that both HTTP clients and servers can understand. For example, when a user uploads a document to the server, the browser sends an HTTP POST request and includes the document in the body of the POST message.


1 Answers

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.

like image 135
fresskoma Avatar answered Sep 22 '22 23:09

fresskoma