您好,我在向 PHP 发送 GET 请求时遇到问题,相同的 PHP 在 Web 浏览器中运行时工作正常
这是 PHP 和 Obj-C 的代码片段
PHP
$var1=$_GET['value1'];
$var2=$_GET['value2'];
当我在浏览器中调用它时它工作正常,但从 obj c 我无法成功
对象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 http://madebymany.com/blog/url-encoding-an-nsstring-on-ios例如)以确保您的请求有效。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)