Wednesday, May 1, 2013

NSMutableURLRequest setHTTPBody example ios


setHTTPBody:

Sets the request body of the receiver to the specified data.
- (void)setHTTPBody:(NSData *)data
Parameters of [NSMutableURLRequest setHTTPBody]
data
The new request body for the receiver. This is sent as the message body of the request, as in an HTTP POST request.
Discussion of [NSMutableURLRequest setHTTPBody]
Setting the HTTP body data clears any input stream set by setHTTPBodyStream:. These values are mutually exclusive.
Example of [NSMutableURLRequest setHTTPBody]
NSString *someString = @"blah";
[data appendData:[someString dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:data];
Example of [NSMutableURLRequest setHTTPBody]
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"riderfinder.appspot.com/login"]];
[request setHTTPMethod:@"POST"];
[request setValue:@"text/plain" forHTTPHeaderField:@"Content-type"];

NSString *body = @"username=";
body=[body stringByAppendingString:accountEntered];
body=[body stringByAppendingString:@"&"];
body=[body stringByAppendingString:@"password="];
body=[body stringByAppendingString: passwordEntered];

//NSMutableData *data = [[NSMutableData data] initWithString:body];
NSData *data=[body dataUsingEncoding:NSUTF8StringEncoding];

[request setHTTPBody:data];
Example of [NSMutableURLRequest setHTTPBody]
NSString *post =[[NSString alloc] initWithFormat:@"userName=%@&password=%@",userName.text,password.text];
NSURL *url=[NSURL URLWithString:@"https://localhost:443/SSLLogin/Login.php"];

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

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

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

/* when we user https, we need to allow any HTTPS cerificates, so add the one line code,to tell teh NSURLRequest to accept any https certificate, i'm not sure about the security aspects
*/

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];

NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(@"%@",data);