我想在android中使用HTTP-post后检索php文件发回的数据。我的代码如下所示:
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文件非常简单,它只回显文本“data”。我认为这个问题与“response.getEntity()。toString()”有关但是如何从HttpPost对象中获取作为字符串发回的数据?
原谅我的拼写错误。
答案 0 :(得分: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;
}
答案 1 :(得分:0)
您也可以使用EntityUtils:
String responseBody = EntityUtils.toString(response.getEntity());