1

当我尝试将 json 从我的 iphone 应用程序发送到 php 服务器时,我遇到了一个小问题。

我创建 NSData 对象

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:test];

我将它发送到网络服务器

-(void)send:(NSData *)jsonData{



    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
                                    initWithURL:[NSURL
                                                 URLWithString:@"http://localhost:8888/jsonserver/try2.php"]];
    [request setHTTPMethod:@"POST"];

    [request setHTTPBody:jsonData];

    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
}

我的网络服务器

<?php
    $json = $_POST['json'];
    $person = json_decode($json);    
    $file = fopen('test.txt','w+');
    fwrite($file, $person);
    fclose($file);
?>

我的服务器在文件夹中正确创建了文件,但文件为空

(我的 json 文件在发送到服务器之前类似于 ["a","b","c"])

谢谢你的帮助:P

4

1 回答 1

0

我不了解 iPhone 开发,但看起来您正在消息正文中发送 JSON 数据。要在 PHP 中获取消息的正文,您需要使用以下行:

$json = file_get_contents("php://input");

我还将 iPhone 端的 Content-Type 标头设置为“application/json”。

我不知道这在 iPhone 上是如何工作的,但请记住这一点:POST 通常会采用参数并将它们编码为消息正文中的 HTTP 查询字符串格式,并使用“application/x-www-form-urlencoded”作为Content-Type 标头,因此请确保 iPhone 端的软件没有这样做。

于 2013-01-02T18:10:01.803 回答