2011-12-11 91 views
0

我希望在android中使用HTTP-post後,檢索php文件發回的數據。我的代碼如下所示:如何在發佈到PHP文件後從HttpResponse對象中檢索字符串?

HttpClient client = new DefaultHttpClient(); 
HttpPost post = new HttpPost("http://10.0.2.2/post.php"); 
List <NameValuePair> pairs = new ArrayList<NameValuePair>(); 
pairs.add(new BasicNameValuePair("test", "hejsan")); 

try{ 
    post.setEntity(new UrlEncodedFormEntity(pairs)); 
}catch(UnsupportedEncodingException a){ 
     infoText.setText("failed to post"); 
} 

try{ 
     HttpResponse response = client.execute(post); 
     infoText.setText(response.getEntity().toString()); 
}catch(ClientProtocolException b){ 
     infoText.setText("failed to get response"); 
}catch(IOException e){ 
     infoText.setText("failed IOEXCEPTION"); 
}this code only changes the "TextView" to: org.apache.http.conn 

BasicManagedEntity @ 45f94a68 ......我的PHP文件是一個非常簡單的,它只是回聲文本「數據」。我認爲這個問題與「response.getEntity()。toString()」有關,但是如何從HttpPost對象獲取發回的數據作爲字符串?

請原諒我的拼寫錯誤。

回答

0

您可以使用響應處理..事情是這樣的:

public static String getResponseBody(HttpResponse response) { 
    ResponseHandler<String> responseHander = new BasicResponseHandler(); 
    String responseBody = null; 
    try { 
     responseBody = (String) responseHander.handleResponse(response); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    logger.debug("Response Body Data:" + responseBody); 

    return responseBody; 
} 
+0

什麼是 「logger.debug(」 響應體數據:」 + responseBody );」我的eclipse似乎並不知道「記錄器」...但它的工作原理沒有這一行:O – AlexanderNajafi

+0

這將是Log而不是記錄器,它需要2個參數 – njzk2

0

您還可以使用EntityUtils:

String responseBody = EntityUtils.toString(response.getEntity());