The following code describes a simple example using the POST method (how to transmit data using the POST method)
Here I describe how you can use the POST method.
1. Set a message string with the actual username and password.
NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"];
2. Encode the message string using NSASCIIStringEncoding , as well as the message string that must be sent in NSData format.
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
You need to send the actual length of your data. Calculate the line length of the message.
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
3. Create an Urlrequest with all properties of type HTTP , an HTTP header field with a message line length. Create a URLRequest object and initialize it.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
Set the Url for which you are going to send data to this request.
[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]];
Now set the HTTP method (POST or GET). Write these lines as they are in your code.
[request setHTTPMethod:@"POST"];
Set an HTTP header field with the message data length.
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
Also set the encoded value for the HTTP header.
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
Set HTTPBody urlrequest with postData.
[request setHTTPBody:postData]
4. Now create the URLConnection object. Initialize it using URLRequest.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
It returns an initialized url connection and starts loading data for the url request. You can check if the URL connection is correct or not using only the if / else statement as shown below.
if(conn) { NSLog(@"Connection Successful"); } else { NSLog(@"Connection could not be made"); }
5 .. To get data from an HTTP request, you can use the delegate methods provided by the URLConnection class reference. Delegate methods are given below.
// This method is used to receive the data which we get using post method. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data // This method receives the error report in case of connection is not made to server. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error // This method is used to process the data after connection has made successfully. - (void)connectionDidFinishLoading:(NSURLConnection *)connection
Also see This and This is the documentation for the POST method.
And here is the best source code example of the HTTPPost method.