0

似乎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);

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

4

1 回答 1

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 );
}

参考文章

于 2012-12-02T19:56:55.070 回答