且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何以字符串形式获取 HTTP 响应正文?

更新时间:2022-05-30 05:34:03

我能想到的每个库都返回一个流.你可以使用 IOUtils.toString() 来自 Apache CommonsIO 在一个方法调用中将 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.