【问题标题】:Receive data from PHP script with NSURLRequest使用 NSURLRequest 从 PHP 脚本接收数据
【发布时间】:2012-04-10 13:02:55
【问题描述】:

我有一个使用 NSURLRequest 和 NSURLConnexion 将数据发送到 PHP 脚本的应用程序。我想要的是用 post 方法发送一个像“Hello world”这样的数据,我想在我的应用程序上显示“Hello world from myPHPScript.php!”但我没有 web 服务经验,特别是 n PHP。

这是我发送请求的 Objective-c 代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL

                                URLWithString:@"http://localhost:8888/testNSURL/index.php"]

                                cachePolicy:NSURLRequestUseProtocolCachePolicy

                                timeoutInterval:60.0];

    [request setHTTPMethod:@"POST"];
    NSString *postString = @"myVariable=Hello world !";
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];

    if (theConnection) {

        receiveData = [NSMutableData data]; 

}

这是我的 PHP 代码:

<?php
if(isset($_REQUEST["myVariable"])) {
    echo json_encode("Hello from index.php !");
}
else    echo json_encode('Request failed');
?>

我的问题是:

  • 我的 PHP 代码是否正确?
  • 如何在我的 obj-c 应用程序中捕获 echo json_encode("Hello from index.php !");

【问题讨论】:

    标签: php objective-c web-services nsurlconnection nsurlrequest


    【解决方案1】:

    我个人在将内容发布到服务器时使用ASIFormDataRequest。当您从此方法获取信息时,您可以执行以下操作来获取服务器上所有已回显的数据/字符串值:

    - (void)requestFinished:(ASIHTTPRequest *)aRequest {
        NSData *responseData = [aRequest responseData];
        NSString *responseString = [aRequest responseString];
    }
    

    从数据信息中获取字符串是这样完成的:

    [[NSString alloc] initWithData:responseData encoding:NSASCIIStringEncoding]
    

    【讨论】:

    • 我使用了它,但是无论有没有 ARC,我都有很多错误/警告,这就是我使用 NSURLRequest / NSURLConnexion 的原因
    • 哦,从来没有真正遇到过任何问题。也许我可以帮助你解决这些错误?
    • 我还添加了从 nsdata 获取字符串的方法 :)
    • 好吧,我用上面的代码替换了所有使用 ASIHTTPRequest 的东西:/
    • 那么你想获取php服务器输出的字符串吗?如果是这样,您可以使用我添加的第二段代码。
    猜你喜欢
    • 1970-01-01
    • 2016-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-22
    • 1970-01-01
    相关资源
    最近更新 更多