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

===============>>#1 票数: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;
}

===============>>#2 票数:0

您还可以使用EntityUtils:

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

  ask by AlexanderNajafi translate from so

未解决问题?本站智能推荐: