Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURLRequest: How to change httpMethod "GET" to "POST"

GET Method, it works fine.

url: http://myurl.com/test.html?query=id=123&name=kkk


I do not have concepts of POST method. Please help me.

How can I chagne GET method to POST method?


url: http://testurl.com/test.html

[urlRequest setHTTPMethod:@"POST"];

like image 283
ChangUZ Avatar asked Oct 13 '11 06:10

ChangUZ


2 Answers

try this

NSString *post = [NSString stringWithFormat:@"username=%@&password=%@",username.text,password.text];
NSLog(@"%@",post);
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:@" server link here"]]];
[request setHTTPMethod:@"POST"];
NSString *json = @"{}";
NSMutableData *body = [[NSMutableData alloc] init];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;  
NSError *error = [[NSError alloc] init];  
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];  
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"Response Code: %d", [urlResponse statusCode]);

if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300) 
{
    NSLog(@"Response: %@", result);
}
like image 55
sarath Avatar answered Sep 27 '22 20:09

sarath


// create mutable request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];       
// set GET or POST method
[request setHTTPMethod:@"POST"];
// adding keys with values
NSString *post = @"query=id=123&name=kkk";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];
[request addValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];
like image 32
Nekto Avatar answered Sep 27 '22 20:09

Nekto