2013-01-02 54 views
0

我正在編寫一個Android應用程序,我想發送一些JSON數據到PHP服務器。 POST請求確實去了服務器,但在我的server.php腳本中,我檢查了$ _POST變量,它是空的。 TCP/IP監視器不在Eclipse ADT中,wireshark不顯示localhost請求,所以我看不到實際發送的內容。那麼是否有人知道發送的內容以及如何在PHP中訪問它?或者我在代碼中犯了一個錯誤?

JSONObject json = new JSONObject(); 

    try { 
     json.put("dog", "cat"); 
    } catch (JSONException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

    HttpURLConnection urlConnection = null; 
    try { 
     URL url = new URL("http://10.0.2.2/server.php"); 
     urlConnection = (HttpURLConnection)url.openConnection(); 
     urlConnection.setRequestProperty("Content-Type", "application/json"); 
     urlConnection.setRequestProperty("Accept", "application/json"); 
     urlConnection.setRequestMethod("POST");   
     urlConnection.setDoOutput(true); 
     OutputStreamWriter os = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"); 
     os.write(json.toString()); 
     os.close(); 
    } 
+0

你從服務器得到什麼迴應? – mt0s

+0

檢查$ _REQUEST,看看你得到了什麼。 –

+0

@ t0s它發回我的server.php頁面的HTML。 – sonicboom

回答

5

試試吧。

JSONObject json = new JSONObject(); 

    try { 
     json.put("dog", "cat"); 
    } catch (JSONException e1) { 
     // TODO Auto-generated catch block 
     e1.printStackTrace(); 
    } 

HttpClient localDefaultHttpClient=new DefaultHttpClient(); 
     HttpPost lotlisting = new HttpPost("http://10.0.2.2/server.php"); 
     ArrayList localArrayList = new ArrayList(); 
     localArrayList.add(new BasicNameValuePair("json",json.toString())); 
     try { 
      lotlisting.setEntity(new UrlEncodedFormEntity(localArrayList)); 
      String str = EntityUtils.toString(localDefaultHttpClient.execute(lotlisting).getEntity()); 

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

你會得到str變量的輸出;

1

我認爲缺少刷新 試試os.flush();之後os.write(..)

0

請勿使用$ _POST。在用戶服務器上做這樣的事情

$json = file_get_contents('php://input'); 
    $animals= json_decode($json,true); 

    //you can do 
    echo $animals['dog'];