用PHP解析JSON POST请求 [英] JSON POST request parsing in PHP
本文介绍了用PHP解析JSON POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在java中生成了一个包含JSON对象的HTMLPost请求,并希望用PHP解析它。
I've generate an HTMLPost Request containing a JSON object in java and would like to parse it in 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特殊字符是编码的。
I guess this is because the JSON special characters are encoded.
json_decode返回空响应
The json_decode return empty response
知道为什么吗?
推荐答案
您实际上是在发布一个HTTP表单实体( application / x-www-form-),而不是POST一个
),单值对json =(编码json)。 application / json
实体。 urlencoded
Instead of POSTing an application/json
entity, you are actually posting an HTTP form entity (application/x-www-form-urlencoded
) with a single value pair json=(encoded 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"));
这篇关于用PHP解析JSON POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文