我希望在android中使用HTTP发布后检索由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文件是一个非常简单的文件,它仅回显文本“数据”。我认为问题与“ response.getEntity()。toString()”有关,但是如何从HttpPost对象获取作为字符串发送回的数据呢?
您可以使用响应处理程序。类似这样的东西:
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;
}
您也可以使用EntityUtils:
String responseBody = EntityUtils.toString(response.getEntity());