如何在iOS中向PHP发送GEt请求 [英] How to send GEt request to PHP in iOS

查看:80
本文介绍了如何在iOS中向PHP发送GEt请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨我在向PHP发送GET请求时遇到问题,在Web浏览器中运行时,同样的PHP工作正常
这里是PHP和Obj-C
PHP的代码片段

Hi i have problem in sending GET request to a PHP, same PHP works fine when running it in web browser here are the code snippet of both the PHP and Obj-C PHP

$var1=$_GET['value1'];
$var2=$_GET['value2'];

当我在浏览器中调用此内容时,如 http://sample.com/sample.php?value1=hi&value2=welcome
它工作正常,但来自obj ci无法成功
obj C

when i call this in browser like http://sample.com/sample.php?value1=hi&value2=welcome it works fine, but from obj c i could't get succeed 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请求没有正文,传递的数据应该附加到网址上。因此,为了模仿您在浏览器中所做的请求,它就像这样。

The problem is that you set HTTPBody (by calling setHTTPBody on your request object) whilst GET-requests doesn't have a body, the passed data should be appended to the url instead. So to mimic the request your did in your browser it would simply be like this.

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 例如)确保您的请求有效。

You should of course make sure to properly encode the values of your querystring (see http://madebymany.com/blog/url-encoding-an-nsstring-on-ios for an example) to make sure that your request is valid.

这篇关于如何在iOS中向PHP发送GEt请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆