0

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

当我使用这个 php 代码来查看我是否正在接收一个字符串以及我得到什么时:

POST: 
Array
(
)



 GET: 
Array
(
    [data] => 
)

这是我的安卓代码:

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

有人看到我做错了吗?

4

1 回答 1

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);
  .....
  }
于 2013-01-04T08:01:14.157 回答