【问题标题】:JSON POST request parsing in PHPPHP中的JSON POST请求解析
【发布时间】:2012-01-13 13:07:28
【问题描述】:

我在 java 中生成了一个包含 JSON 对象的 HTMLPost 请求,并希望在 PHP 中对其进行解析。

public static String transferJSON(JSONObject j) {
    HttpClient httpclient= new DefaultHttpClient();
    HttpResponse response;
    HttpPost httppost= new HttpPost(SERVERURL);
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
    nameValuePairs.add(new BasicNameValuePair("json", j.toString()));

    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    response = httpclient.execute(httppost);  
}

在服务器上

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

  // input = "json=%7B%22locations%22%3A%5B%7B%22..."
  $input = file_get_contents('php://input');

  // jsonObj is empty, not working
  $jsonObj = json_decode($input, true);

我猜这是因为 JSON 特殊字符被编码了。

json_decode 返回空响应

知道为什么吗?

【问题讨论】:

    标签: java php json post


    【解决方案1】:

    您实际上是在发布具有单个值对 json=(encoded json) 的 HTTP 表单实体 (application/x-www-form-urlencoded),而不是发布 application/json 实体。

    而不是

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);  
    nameValuePairs.add(new BasicNameValuePair("json", j.toString()));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    

    试试

     httppost.setEntity(new StringEntity(j.toString(),"application/json","UTF-8"));
    

    【讨论】:

    • 感谢比转换输入更好的解决方案。您的带有 3 个字符串的构造函数不存在。我用StringEntity stringEntity = new StringEntity(j.toString(),"UTF-8"); stringEntity.setContentType("application/json");
    • 您使用的 HTTP 客户端/HTTP 组件的版本肯定会有所不同。我刚刚从the latest javadoc中拉出构造函数@
    • 好的,应该是这样。我在 Android 上使用的是 java 版本。
    【解决方案2】:

    这是设计使然:您正在访问需要进行 URL 编码的原始 POST 数据。

    首先在数据上使用urldecode()

    【讨论】:

      【解决方案3】:

      试试这个:

      //remove json=
      $input = substr($input, 5);
      
      //decode the url encoding
      $input = urldecode($input);
      
      $jsonObj = json_decode($input, true);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-01-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多