
[英]How to retrieve List <String> from HttpResponse object in Java
[英]How do i retrieve a string from a HttpResponse object after posting to a PHP-file?
我希望在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 文件是一个非常简单的文件,它只回显文本“数据”。 我认为问题与“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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.