嗨我在向PHP发送GET请求时遇到问题,在Web浏览器中运行时,同样的PHP工作正常 这是PHP和Obj-C的代码片段 PHP
$var1=$_GET['value1'];
$var2=$_GET['value2'];
当我在浏览器中调用此内容时http://sample.com/sample.php?value1=hi&value2=welcome 它工作正常,但从obj c我不能成功 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];
请帮帮忙?
答案 0 :(得分:5)
问题是您设置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以获取示例)以确保您的请求有效。