How to send GEt request to PHP in iOS

馋奶兔 提交于 2019-12-04 09:01:37

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/11778318/how-to-send-get-request-to-php-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!