Php 无法从应用程序接收JSON数据
Android应用程序发送JSON对象似乎没有问题,但当我收到时,我得到一个: “注意:未定义索引” 发送对象的代码如下所示:Php 无法从应用程序接收JSON数据,php,android,json,http-post,Php,Android,Json,Http Post,Android应用程序发送JSON对象似乎没有问题,但当我收到时,我得到一个: “注意:未定义索引” 发送对象的代码如下所示: public void sendJson( String name1, String name2 ) throws JSONException { HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://example.
public void sendJson( String name1, String name2 ) throws JSONException {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
HttpResponse response;
JSONObject json = new JSONObject();
try {
json.put("name1", name1);
json.put("name2", name2);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.getParams().setParameter("json", json); // new code
//Execute HTTP POST request
httppost.setEntity(se);
response = httpclient.execute(httppost);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
} catch ( ClientProtocolException e ) {
e.printStackTrace();
} catch ( IOException e ) {
e.printStackTrace();
}
}
在服务器端:
$json = $_POST['name1'];
$decoded = json_decode($json, TRUE);
我收到了未定义索引通知。编辑-修改我的答案: 看起来您正在发送一个名为
json
的参数,其中包含“name1”和“name2”作为数据
类似的方法应该可以工作:在PHP端,您需要首先解码JSON:
$json = json_decode($_POST['json']);
然后您可以访问name1和name2:
$name1 = $json['name1'];
$name2 = $json['name2'];
如果仍然出现错误,我建议打印出$\u POST和$\u get对象,并查看数据是如何发送的。然后您将知道如何访问它
更新: 您得到的结果
array(0){}
意味着PHP没有从您的请求中获得任何参数(get或POST)。您可以尝试以下不同的android示例:
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://example.com/JSON_FOLDER/JSON2/parseData.php");
post.setHeader("Content-type", "application/json");
post.setHeader("Accept", "application/json");
JSONObject json = new JSONObject();
json.put("name1", name1);
json.put("name2", name2);
post.setEntity(new StringEntity(json.toString(), "UTF-8"));
HttpResponse response = client.execute(post);
if( response != null ) {
str = inputStreamToString(response.getEntity().getContent()).toString();
Log.i("DATA", "Data send== " + str );
}
我建议您在服务器端或客户端查看回复的原始结果。例如:file\u get\u contents('php://input'); 我试过了,但没有结果在服务器端,您将回复转储到日志文件中(例如php syslog())。在客户端:取决于你的平台,我不知道android。最简单的可能是使用像Wireshark这样的网络嗅探器。我尝试了使用$\u GET、$\u POST和“json”、“name1”、“name2”的所有可能组合,结果总是一样的。未定义的索引。我还从应用程序中删除了set'json'参数,但仍然是相同的它会告诉您是否有任何参数进入PHP代码。