【问题标题】:Missing json array in post request to php对 php 的发布请求中缺少 json 数组
【发布时间】:2013-12-16 17:34:31
【问题描述】:

我正在尝试将 json 对象从 Android 设备发送到 PHP 以将其插入数据库,但服务器找不到它。我做错了什么?谢谢。

脚本在 isset 检查中失败。

PHP 脚本:

    <?php

$json_array = json_decode($_POST['messages']) -> messages;

if(isset($json_array))
{
    //connect to database and do insertions.
} else
{
    echo "Not found array with messages in POST request\n";
}

发布请求包含:

{"messages":[{"message":"Hello. Test from ukraine","id":1,"from_sender":"1111-111-1111","box":"2","type":"sms"}]}

它是这样形成的:

HttpClient httpClient = new DefaultHttpClient();

            try {
                HttpPost httpPost = new HttpPost(BASE_URL + "/josyko.php");
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("messages", request.toString()));
                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                result = EntityUtils.toString(httpResponse.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }

【问题讨论】:

  • var_dump($_POST, $json_array);

标签: php json


【解决方案1】:

您可以使用:http://php.net/manual/en/reserved.variables.httprawpostdata.php

$json_array = json_decode($HTTP_RAW_POST_DATA) -> messages;

或者更好的解决方案:

file_get_contents('php://input'); // instead of $HTTP_RAW_POST_DATA

【讨论】:

  • 不要使用$HTTP_RAW_POST_DATAPHP Manual says,“访问原始 POST 数据的首选方法是 php://input”。
  • 在我的本地机器和虚拟主机上,它正在使用 $_POST,但在其他主机上它无法正常工作...我认为问题不在于 $HTTP_RAW_POST_DATA...
  • stackoverflow.com/questions/8391302/… 在这里找到答案。谢谢大家帮忙
猜你喜欢
  • 2017-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-07
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 2017-12-19
相关资源
最近更新 更多