无法从应用程序接收JSON数据

时间:2012-12-02 19:48:27

标签: 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.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);

我得到了未定义的索引通知。

1 个答案:

答案 0 :(得分:0)

编辑 - 修改我的回答:

您似乎发送了一个名为json的参数,其中包含“name1”和“name2”作为数据。

这样的事情应该有效:在PHP方面,你需要首先解码JSON:

$json = json_decode($_POST['json']);

然后你可以访问name1和name2:

$name1 = $json['name1'];
$name2 = $json['name2'];

如果仍然出现错误,我建议打印出$ _POST和$ _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 );
}

Reference Article

相关问题