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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2573064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 09:22:56  来源:igfitidea点击:

How to print out returned message from HttpResponse?

java.netandroidhttpresponse

提问by chobo2

I have this code on my Android phone.

我的 Android 手机上有此代码。

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

I have a asp.net webform application that has in the page load this

我有一个 asp.net webform 应用程序,它在页面中加载了这个

 Response.Output.Write("It worked");

I want to grab this Response from the HttpReponse and print it out. How do I do this?

我想从 HttpReponse 中获取这个 Response 并将其打印出来。我该怎么做呢?

I tried response.getEntity().toString()but it just seems to print out the address in memory.

我试过了,response.getEntity().toString()但它似乎只是打印出内存中的地址。

Thanks

谢谢

采纳答案by CommonsWare

Use ResponseHandler. One line of code. See hereand herefor sample Android projects using it.

使用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
    }
} 

add combination of this post and complete HttpClient at - http://www.androidsnippets.org/snippets/36/

添加这篇文章的组合并在 - http://www.androidsnippets.org/snippets/36/完成 HttpClient

回答by hnviet

I would just do it the old way. It's a more bulletproof than ResponseHandler, in case you get different content types in the response.

我只会用旧的方式来做。它比 ResponseHandler 更防弹,以防您在响应中获得不同的内容类型。

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

回答by Sanghita

This code will return the entire response message in respondas a String, and status code in rsp, as an int.

此代码将在返回整个响应消息响应一个String,和状态码在RSP,作为一个int

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

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

回答by Lunf

I used the following code

我使用了以下代码

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();

回答by JimiLoe

The simplest approach is probably using org.apache.http.util.EntityUtils:

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

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

It reads the contents of an entity and returns it as a String. The content is converted using the character set from the entity (if any), failing that, "ISO-8859-1" is used.

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

If necessary, you can pass a default character set explicitly - e.g.

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

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

It gets the entity content as a String, using the provided default character set if none is found in the entity. If the passed default character set is null, the default "ISO-8859-1" is used.

如果在实体中找不到任何内容,则使用提供的默认字符集获取实体内容作为字符串。如果传递的默认字符集为空,则使用默认的“ISO-8859-1”。