嗨,我在向PHP发送GET请求时遇到问题,在Web浏览器中运行该PHP时,同样的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];
请帮忙?
最佳答案
问题是您设置了HTTPBody(通过在请求对象上调用setHTTPBody
),而GET-requests没有主体,传递的数据应该附加到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),以确保您的请求有效。
关于php - 如何在iOS中将GEt请求发送到PHP,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11778318/