[发布到PHP文件后如何从HttpResponse对象中检索字符串?

问题描述 投票:0回答:2

我希望在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对象获取作为字符串发送回的数据呢?

java android post entity httpresponse
2个回答
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
投票

您也可以使用EntityUtils:

String responseBody = EntityUtils.toString(response.getEntity());
© www.soinside.com 2019 - 2024. All rights reserved.