如何向iOS发送GEt请求到PHP

问题描述:

您好,我在向PHP发送GET请求时遇到问题,在网络浏览器中运行它时,PHP也能正常工作 这里是PHP和Obj-C的代码片段 PHP如何向iOS发送GEt请求到PHP

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

当我把这个像http://sample.com/sample.php?value1=hi&value2=welcome 它工作正常的浏览器,但是从obj获得的CI头被埋获得成功 OBJç

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

请帮助?

+1

您尚未在您的请求中的任何位置指定value1和value2。你可以做的只是将这些URL附加在@“http://sample.com/sample.php?value1=%@”上,valueString – 2012-08-02 13:30:53

+0

谢谢@SiddharthDhingra那么工作! – Satheesh 2012-08-03 05:20:13

问题是,您设置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]; 

你当然应该确保正确编码的查询字符串的值(见http://madebymany.com/blog/url-encoding-an-nsstring-on-ios为例),以确保您的请求是有效的。

+0

这是真棒哥们谢谢你! – Satheesh 2012-08-03 05:19:37

+0

GET请求可以拥有一个正文,并且大多数服务器都支持该正文。想象一下,需要使用大于url中允许的最大字节数的过滤器对资源执行GET请求的情况。 – Guillermo 2013-04-16 16:35:36