gpt4 book ai didi

php - 发送json数据到php返回null

转载 作者:行者123 更新时间:2023-12-01 18:50:20 25 4
gpt4 key购买 nike

我正在尝试通过json格式将数据数组(在字典中)发送到服务器端的php文件,以便以后将数据存储到MySQL数据库中。但是,看起来php接收的数据对象始终为null。

这是Objective-C行:

NSURL *url = [NSURL URLWithString:@"http://myaddress/upload.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:@"application/json; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:self.sentData];

NSError *error = nil;
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

if (error) NSLog(@"%s: NSURLConnection error: %@", __FUNCTION__, error);
NSString *responseString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"responseString: %@",responseString);

这是php行:
<?php

$json_data=file_get_contents('php://input');
$post_data = json_decode($json_data);

if (is_array($post_data))
$response = array("status" => "ok", "code" => 0, "original request" => $post_data);
else
$response = array("status" => "error", "code" => -1, "original_request" => $post_data);

$processed = json_encode($response);
echo $processed;

?>

Xcode上的调试消息如下:
2015-07-19 17:34:35.900 PhpPostTest[1531:557248] responseString: {"status":"error","code":-1,"original_request":null}

看起来连接正常,但是响应字符串指示php端接收的数据为空。有人可以建议这里有什么潜在问题吗?

最佳答案

每当您尝试解码的JSON格式不正确时,json_decode()将返回NULL

您可以运行echo $json_data;来验证您的JSON实际上是JSON。

关于php - 发送json数据到php返回null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31506756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com