2012-12-02 71 views
0

似乎Android應用程序發送JSON對象沒有問題,但是當我收到我得到一個:無法從應用程序接收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); 

和我得到了不確定的指標通知書。

+0

我建議你看一看原始的結果說,無論是在服務器或客戶端。 – arkascha

+0

這樣的:*** file_get_contents('php:// input'); ***我試過但沒有結果 – t0s

+0

在服務器端你把應答轉儲到日誌文件中(例如php syslog())。在客戶端:取決於你的平臺,我不知道android。最簡單的可能是使用像Wireshark這樣的網絡嗅探器。 – arkascha

回答

0

編輯 - 修改我的答案:

看來您發送稱爲json一個參數包含「NAME1」和「NAME2」的數據。

像這樣的東西應該工作:在PHP端你需要的JSON第一解碼:

$json = json_decode($_POST['json']); 

,那麼你可以訪問NAME 1和NAME:

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

Reference Article

+0

我嘗試了所有可能的$ _GET,$ _POST和'json','name1','name2'的組合,結果總是一樣的。未定義的索引。 我也從應用程序中刪除了設置'json'參數,但仍然一樣。 – t0s

+0

做一個'var_dump($ _ REQUEST);'它會告訴你是否有任何參數正在向PHP代碼傳送。 – Levi

+0

** array(0){} ** – t0s

相關問題