Sat*_*esh 2 php objective-c nsurlrequest ios
嗨,我有一个问题,发送GET请求到PHP,相同的PHP在Web浏览器中运行时工作正常这里是PHP和Obj-C PHP的代码片段
$var1=$_GET['value1'];
$var2=$_GET['value2'];
Run Code Online (Sandbox Code Playgroud)
当我在浏览器中调用这个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];
Run Code Online (Sandbox Code Playgroud)
请帮忙?
问题是您设置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];
Run Code Online (Sandbox Code Playgroud)
您当然应该确保正确编码查询字符串的值(请参阅http://madebymany.com/blog/url-encoding-an-nsstring-on-ios以获取示例)以确保您的请求有效.
| 归档时间: |
|
| 查看次数: |
5100 次 |
| 最近记录: |