Satheesh
Satheesh

Reputation: 371

How to send GEt request to PHP in iOS

Hi i have problem in sending GET request to a PHP, same PHP works fine when running it in web browser here are the code snippet of both the PHP and Obj-C PHP

$var1=$_GET['value1'];
$var2=$_GET['value2'];

when i call this in browser like http://sample.com/sample.php?value1=hi&value2=welcome it works fine, but from obj c i could't get succeed obj C

 NSString *url =[NSString stringWithFormat:@"http://sample.com/sample.php"];
    NSData *data = [@"sample.php" dataUsingEncoding:NSUTF8StringEncoding];
    NSLog(@"%@",url);
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    [req setHTTPMethod:@"GET"];
    [req setHTTPBody:data];
    NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:req delegate:self]autorelease];
    [connection start];

Please help?

Upvotes: 2

Views: 5214

Answers (1)

Karl-Johan Sjögren
Karl-Johan Sjögren

Reputation: 17532

The problem is that you set HTTPBody (by calling setHTTPBody on your request object) whilst GET-requests doesn't have a body, the passed data should be appended to the url instead. So to mimic the request your did in your browser it would simply be like this.

NSString *url =[NSString stringWithFormat:@"http://sample.com/sample.php?value1=hi&value2=welcome"];
NSLog(@"%@",url);
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
[req setHTTPMethod:@"GET"]; // This might be redundant, I'm pretty sure GET is the default value
NSURLConnection *connection = [[[NSURLConnection alloc] initWithRequest:req delegate:self]autorelease];
[connection start];

You should of course make sure to properly encode the values of your querystring (see http://madebymany.com/blog/url-encoding-an-nsstring-on-ios for an example) to make sure that your request is valid.

Upvotes: 5

Related Questions