首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何获取字符串形式的HTTP响应正文?

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

Stack Overflow用户
提问于 2011-04-24 17:25:38
回答 13查看 518.7K关注 0票数 176

我知道曾经有一种方法可以在Apache Commons中获得它,如下所示:

http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html

...and这里有一个例子:

http://www.kodejava.org/examples/416.html

...but我认为这是被弃用的。

有没有其他方法可以在Java中发出http get请求,并以字符串而不是流的形式获取响应体?

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2011-04-24 17:33:49

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

代码语言:javascript
复制
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作为最佳猜测,而不是使用本地系统默认值。

票数 113
EN

Stack Overflow用户

发布于 2012-12-06 19:08:22

以下是我的工作项目中的两个示例。

使用EntityUtilsHttpEntity

HttpResponse响应=httpClient.execute(新的HttpGet(URL));HttpEntity entity = response.getEntity();String responseString = EntityUtils.toString(entity,"UTF-8");HttpEntity BasicResponseHandler

HttpResponse response =httpClient.execute(新的HttpGet地址);String responseString =新的URL

票数 306
EN

Stack Overflow用户

发布于 2012-03-07 05:37:27

下面是我使用Apache中的httpclient库参与的另一个简单项目的示例:

代码语言:javascript
复制
String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

只需使用EntityUtils获取字符串形式的响应体即可。非常简单。

票数 52
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5769717

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档