Android不发送json字符串

时间:2013-01-04 07:52:22

标签: php android json http-post

我正面临着我发送jsonstring的问题,但字符串是空的。

当我使用这个PHP代码来查看我是否收到一个字符串以及我得到的内容:

POST: 
Array
(
)



 GET: 
Array
(
    [data] => 
)

这是我的Android代码:

HttpClient httpclient = new DefaultHttpClient(); 

        HttpPost httppost = new HttpPost("http://www.myserver.nl/locatie.php?data="); 
        httppost.setHeader("Content-type", "application/json"); 

        // Create json object here... 
        json = new JSONObject(); 
        try { 
            json.put("id", "0612838"); 
            json.put("longitude", "-143.406417"); 
            json.put("latitude", "32.785834"); 
            json.put("timestamp", "10-10 07:56"); 

        } catch (JSONException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        } 

        /// create StringEntity with current json obejct 

        try { 
        se = new StringEntity(json.toString()); 
        } catch (UnsupportedEncodingException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        } 

        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); 
        httppost.setEntity(se); 

        try { 
        response = httpclient.execute(httppost); 
        String temp = EntityUtils.toString(response.getEntity()); 
        } catch (IOException e) { 
        // TODO Auto-generated catch block 
        e.printStackTrace(); 
        } 

有人看到我做错了吗?

1 个答案:

答案 0 :(得分:1)

使用NameValuePair

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httpost = new HttpPost("http://www.myserver.nl/locatie.php");

    json = new JSONObject(); 
    try { 
        json.put("id", "0612838"); 
        json.put("longitude", "-143.406417"); 
        json.put("latitude", "32.785834"); 
        json.put("timestamp", "10-10 07:56"); 

    } catch (JSONException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 

    /// create StringEntity with current json obejct 

    try { 
    se = new StringEntity(json.toString()); 

        List <NameValuePair> nvps = new ArrayList <NameValuePair>();
        nvps.add(new BasicNameValuePair("data", se));

        httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));


        System.out.println("send about to do post");
        HttpResponse response = httpclient.execute(httpost);
        System.out.println("send post done");
        HttpEntity entity = response.getEntity();
           ....


    } catch (UnsupportedEncodingException e) { 
    // TODO Auto-generated catch block 
    e.printStackTrace(); 
    } 

服务器端

  if (isset($_POST["data"]))
  {                                                                                                                                       
  // Takes a JSON encoded string and converts it into a PHP variable.
  $sub = json_decode($_POST"data"],true);
  .....
  }