Sending an HTTP POST request on iOS Sending an HTTP POST request on iOS ios ios

Sending an HTTP POST request on iOS


The following code describes a simple example using POST method.(How one can pass data by POST method)

Here, I describe how one can use of POST method.

1. Set post string with actual username and password.

NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",@"username",@"password"]; 

2. Encode the post string using NSASCIIStringEncoding and also the post string you need to send in NSData format.

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 

You need to send the actual length of your data. Calculate the length of the post string.

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

3. Create a Urlrequest with all the properties like HTTP method, http header field with length of the post string. Create URLRequest object and initialize it.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 

Set the Url for which your going to send the data to that request.

[request setURL:[NSURL URLWithString:@"http://www.abcde.com/xyz/login.aspx"]]; 

Now, set HTTP method (POST or GET). Write this lines as it is in your code.

[request setHTTPMethod:@"POST"]; 

Set HTTP header field with length of the post data.

[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 

Also set the Encoded value for HTTP header Field.

[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];

Set the HTTPBody of the urlrequest with postData.

[request setHTTPBody:postData];

4. Now, create URLConnection object. Initialize it with the URLRequest.

NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

It returns the initialized url connection and begins to load the data for the url request. You can check that whether you URL connection is done properly or not using just if/else statement as below.

if(conn) {    NSLog(@"Connection Successful");} else {    NSLog(@"Connection could not be made");}

5. To receive the data from the HTTP request , you can use the delegate methods provided by the URLConnection Class Reference.Delegate methods are as 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 Refer This and This documentation for POST method.

And here is best example with source code of HTTPPost Method.


-(void)sendingAnHTTPPOSTRequestOniOSWithUserEmailId: (NSString *)emailId withPassword: (NSString *)password{//Init the NSURLSession with a configurationNSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];//Create an URLRequestNSURL *url = [NSURL URLWithString:@"http://www.example.com/apis/login_api"];NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];//Create POST Params and add it to HTTPBodyNSString *params = [NSString stringWithFormat:@"email=%@&password=%@",emailId,password];[urlRequest setHTTPMethod:@"POST"];[urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];//Create taskNSURLSessionDataTask *dataTask = [defaultSession dataTaskWithRequest:urlRequest completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {    //Handle your response here    NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];     NSLog(@"%@",responseDict);}];   [dataTask resume];}


I am not really sure why, but as soon as I comment out the following method it works:

connectionDidFinishDownloading:destinationURL:

Furthermore, I don't think you need the methods from the NSUrlConnectionDownloadDelegate protocol, only those from NSURLConnectionDataDelegate, unless you want some download information.