如何在Java中将http响应主体作为字符串获取?

问题

我知道曾经有一种方法可以通过这里记录的apache commons来获取它:http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html这里有一个例子:
http://www.kodejava.org/examples/416.html
但我相信这已被弃用了。是否还有其他方法可以在java中生成http get请求并将响应主体作为字符串而不是流来获取?


#1 热门回答(205 赞)

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

  • 使用EntityUtils和HttpEntity HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity,"UTF-8");
    的System.out.println(responseString);
  • 使用BasicResponseHandler HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler()。handleResponse(response);
    的System.out.println(responseString);

#2 热门回答(79 赞)

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

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作为最佳猜测,而不是使用本地系统默认值。


#3 热门回答(44 赞)

这是我正在使用Apache的httpclient库的另一个简单项目的示例:

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将响应主体作为String抓取。很简单。