Here I just describe how to 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 a 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] autorelease];
Set the Url for which you are going to send data to this request.
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.abcde.com/xyz/login.aspx"]]];
Now set the HTTP method (POST or GET). Write these lines as 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:@"Current-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 you connected is running correctly or if the if / else statement is not used, 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. The delegation methods are as follows.
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
The above method is used to obtain the data that we receive using the Method message.
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
This method, which you can use to get an error report in case of connection to the server, is not performed.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
The above method is used to process the data after the connection is successful.