如何在Java中将http响应主体作为字符串获取? [英] How can I get an http response body as a string in Java?

查看:184
本文介绍了如何在Java中将http响应主体作为字符串获取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道过去有一种方法可以通过apache commons获取它,如下所示:
http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html
以及此处的示例:

I know there used to be a way to get it with apache commons as documented here: http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html and an example here:

http://www.kodejava.org/examples/416。 HTML

但我相信这已被弃用。
有没有其他方法可以在java中生成http get请求并将响应正文作为字符串而不是流来获取?

but i believe this is deprecated. Is there any other way to make an http get request in java and get the response body as a string and not a stream?

推荐答案

我能想到的每个库都会返回一个流。您可以使用 IOUtils.toString() noreferrer> Apache Commons IO 在一次方法调用中将 InputStream 读入 String 。例如:

Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:

URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

更新:我更改了上面的示例,使用了来自的内容编码响应如果可用。否则它将默认为UTF-8作为最佳猜测,而不是使用本地系统默认值。

Update: I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.

这篇关于如何在Java中将http响应主体作为字符串获取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆