2

嗨,我在向 PHP 发送 GET 请求时遇到问题,相同的 PHP 在 Web 浏览器中运行时工作正常这里是 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];

请帮忙?

4

1 回答 1

5

问题是您设置了 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示例)以确保您的请求有效。

于 2012-08-02T13:31:04.910 回答