如何从HttpResponse打印出返回的消息?

29

我在我的安卓手机上有这段代码。

   URI uri = new URI(url);
   HttpPost post = new HttpPost(uri);
   HttpClient client = new DefaultHttpClient();
   HttpResponse response = client.execute(post);

我有一个asp.net的WebForm应用程序,在页面加载中有以下代码:

 Response.Output.Write("It worked");
我想从HttpResponse中获取Response并将其打印出来。我该如何做?
我尝试过response.getEntity().toString(),但它似乎只是打印出内存中的地址。
谢谢。
5个回答

40

使用ResponseHandler。只需一行代码即可。在这里这里查看使用它的示例Android项目。

public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.yoursite.com/user");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "12345"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        ResponseHandler<String> responseHandler=new BasicResponseHandler();
        String responseBody = httpclient.execute(httppost, responseHandler);
        JSONObject response=new JSONObject(responseBody);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
} 

将该帖子和完整的HttpClient组合在一起,可以参考- http://www.androidsnippets.org/snippets/36/


这在哪个Android API版本中可用?我可能需要重新编写一些代码:D - user132014
我认为它从一开始就存在,或者至少从Android 0.9版本开始存在。它是标准的HttpClient 4.x包的一部分。 - CommonsWare

12

我会采用老方法来操作。相对于ResponseHandler,它更加稳妥,因为响应中可能包含不同的内容类型。

ByteArrayOutputStream outstream = new ByteArrayOutputStream();
response.getEntity().writeTo(outstream);
byte [] responseBody = outstream.toByteArray();

8

最简单的方法可能是使用org.apache.http.util.EntityUtils

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

它读取实体的内容并将其作为字符串返回。如果有,使用实体的字符集进行转换,否则使用“ISO-8859-1”。

如有必要,您可以显式传递默认字符集 - 例如:

String message = EntityUtils.toString(response.getEntity(). "UTF-8");

使用提供的默认字符集获取实体内容,并将其作为字符串返回。如果未在实体中找到字符集,则使用传递的默认字符集。如果传递的默认字符集为null,则使用默认的“ISO-8859-1”字符集。


8
我使用了以下代码。
BufferedReader r = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

StringBuilder total = new StringBuilder();

String line = null;

while ((line = r.readLine()) != null) {
   total.append(line);
}
r.close();
return total.toString();

6

这段代码将返回整个响应消息作为字符串 respond,状态码作为整数 rsp

respond = response.getStatusLine().getReasonPhrase();

rsp = response.getStatusLine().getStatusCode();`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接