【问题标题】:Post JSON to PHP Server将 JSON 发布到 PHP 服务器
【发布时间】:2014-02-17 18:13:24
【问题描述】:

我想将一些数据发送到 PHP 文件,我得到的只是{"status":"error","code":-1,"original_request":null}

我的目标 C 代码:

NSMutableDictionary *questionDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:questionTitleString, @"question_title", questionBodyString, @"question_body", nil];


NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://myURL/post.php"]];
[request setHTTPMethod:@"POST"];


NSData *jsonData = [NSJSONSerialization dataWithJSONObject:questionDictionary options:kNilOptions error:nil];

[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];

[request setValue:@"json" forHTTPHeaderField:@"Data-Type"];
[request setValue:[NSString stringWithFormat:@"%d", [jsonData length]] forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody: jsonData];

NSURLConnection *postConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

现在是我的 PHP 代码:

    $postdata = file_get_contents("php://input");
$obj = json_decode($postdata);

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

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

问题是 PHP 接收到来自我的应用程序的请求,但没有收到我发送给它的内容。

【问题讨论】:

  • 不应该是 is_array($obj) 而不是 is_array($post_data) 吗?还有 "original_request" => $obj
  • 我也猜想 json_decode 需要第二个 true 参数才能解码为数组

标签: php ios objective-c json nsurlconnection


【解决方案1】:

当有多个参数时,为什么在 php://input 上直接使用json_decode()

试试这个:

// See the underlying structure of your data; attempt to decode the JSON:
var_dump($_POST);

$data = json_decode($_POST['question_title'], true);
var_dump($data);

$data = json_decode($_POST['question_body'], true);
var_dump($data);

PHP 为我们提供$_POST 超全局是有充分理由的。此外,json_decode($string, true) 将返回一个关联数组。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-25
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多