2013-01-08 16 views
0

我正在使用此代碼將其發送到我的php文件。 該文件看起來像這樣。Json不能使用HttpPost

file_put_contents('dump.txt', "POST: \n" . print_r($_POST, true) . "\n\n\n GET: \n" . print_r($_GET, true)); 

我發送JSON是這樣的:

public void postData(String url,JSONObject json) { 
     // TODO Auto-generated method stub 
     HttpClient httpclient = new DefaultHttpClient(); 
     String object = "?data=" +json.toString(); 
     System.out.println("object:" + object); 

     try { 

      HttpPost httppost = new HttpPost(url.toString()); 
      httppost.setHeader("Content-type", "application/json"); 
      System.out.println("url:" + url.toString()); 
      StringEntity se = new StringEntity(object); 
      System.out.println("json:" + json.toString()); 

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

      HttpResponse response = httpclient.execute(httppost); 
      String temp = EntityUtils.toString(response.getEntity()); 
      System.out.println("response:" + response); 

      int statusCode = response.getStatusLine().getStatusCode(); 
      System.out.println("Statuscode " + statusCode); 

      if(statusCode==200) 
      { 
        Toast.makeText(LbsGeocodingActivity.this, 
              "Verstuurd", 
              Toast.LENGTH_LONG).show(); 

      } 
      else if(statusCode!=200) { 

          Toast.makeText(this, statusCode, Toast.LENGTH_LONG).show(); 
      } 

      /* try { 
       String responseBody = EntityUtils.toString(response.getEntity()); 
     Toast.makeText(this, responseBody, Toast.LENGTH_LONG).show(); 
     } catch (ParseException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
     } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
     }*/ 


     } catch (ClientProtocolException e) { 

     } catch (IOException e) { 
     } 



    } 

日誌文件是這樣的:

01-08 09:36:00.278: I/System.out(1124): object:?data={"id":"69403","timestamp":"08-01-2013 09:36:00","longitude":"-122.084095","latitude":"37.422005"} 
01-08 09:36:00.298: I/System.out(1124): json:{"id":"69403","timestamp":"08-01-2013 09:36:00","longitude":"-122.084095","latitude":"37.422005"} 
01-08 09:36:01.038: I/System.out(1124): response:[email protected] 
01-08 09:36:01.038: I/System.out(1124): Statuscode 200 

但我在dump.txt得到一個空文件

POST: 
Array 
(
) 



GET: 
Array 
(
) 

編輯

的東西是錯誤的setEntity(或某處大約有),因爲當我已經粘貼URL數據=我得到這個從PHP文件:

POST: 
Array 
(
) 



GET: 
Array 
(
    [data] => 
) 
+0

爲什麼您的日誌信息中沒有打印「url:...」? –

+0

因爲我想到安全。它會是這樣的:「http://server.com/locatie.php」 –

回答

0

嘗試

String object = "?data=" +URLEncoder.encode(json.toString(), "UTF-8"); 
+0

沒有,這仍然無法正常工作。還沒有收到任何東西。我知道代碼正在工作。之前測試過 –