如何在iOS中发送GEt请求到PHP

您好,我有发送GET请求到PHP的问题,相同的PHP在网页浏览器中运行时工作正常这里是PHP和Obj-C PHP的代码片段

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

当我在浏览器中调用像http://sample.com/sample.php?value1=hi&value2=welcome它工作正常,但从obj ci不能成功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]; 

请帮忙?

问题是你设置HTTPBody(通过调用请求对象的setHTTPBody ),而GET请求没有正文,传递的数据应该被附加到URL。 所以为了模仿你在浏览器中做的请求,简直就是这样。

 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]; 

您当然应该确保正确地编码查询string的值(例如,请参阅http://madebymany.com/blog/url-encoding-an-nsstring-on-ios )以确保您的请求有效。