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

Dan*_*h94 142 java apache-commons apache-httpclient-4.x

我知道曾经有一种方法可以通过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请求并将响应主体作为字符串而不是流来获取?

小智 256

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

  1. 使用EntityUtilsHttpEntity

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    HttpEntity entity = response.getEntity();
    String responseString = EntityUtils.toString(entity, "UTF-8");
    System.out.println(responseString);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 运用 BasicResponseHandler

    HttpResponse response = httpClient.execute(new HttpGet(URL));
    String responseString = new BasicResponseHandler().handleResponse(response);
    System.out.println(responseString);
    
    Run Code Online (Sandbox Code Playgroud)

  • 我遇到方法1的唯一问题是,当你执行`response.getEntity()`时,实体对象被消耗了,现在它可以作为`responseString`使用.如果你再次尝试执行response.getEntity(),它将返回`IllegalStateException`. (10认同)
  • 什么是httpClient?! (2认同)

Whi*_*g34 97

我能想到的每个库都会返回一个流.你可以使用IOUtils.toString()Apache的百科全书IO读取一个InputStreamString一个方法调用.例如:

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);
Run Code Online (Sandbox Code Playgroud)

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

  • 实际上charset在contentType中指定为"charset = ...",但不在contentEncoding中指定,其中包含类似'gzip'的内容 (8认同)
  • 在许多情况下,这会损坏文本,因为该方法使用系统默认文本编码,该编码因操作系统和用户设置而异. (3认同)

moo*_*ese 48

这是我正在使用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);
}
Run Code Online (Sandbox Code Playgroud)

只需使用EntityUtils将响应主体作为String抓取.非常简单.


McD*_*ell 28

这在具体情况下相对简单,但在一般情况下相当棘手.

HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));
Run Code Online (Sandbox Code Playgroud)

答案取决于Content-Type HTTP响应头.

此标头包含有关有效负载的信息,可能定义文本数据的编码.即使您假设文本类型,也可能需要检查内容本身以确定正确的字符编码.例如,请参阅HTML 4规范,了解有关如何为该特定格式执行此操作的详细信息.

一旦知道编码,就可以使用InputStreamReader来解码数据.

这个答案取决于服务器做正确的事情 - 如果你想处理响应头与文档不匹配的情况,或者文档声明与使用的编码不匹配,那就是另一个鱼.


lka*_*mal 10

下面是使用Apache HTTP Client库以String形式访问响应的简单方法.

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//... 

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);
Run Code Online (Sandbox Code Playgroud)


Eri*_*enz 9

这个怎么样?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));
Run Code Online (Sandbox Code Playgroud)


Aks*_*hay 8

McDowell的回答是正确的.但是,如果您在上面的几个帖子中尝试其他建议.

HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}
Run Code Online (Sandbox Code Playgroud)

然后它将为您提供illegalStateException,指出已经消耗了内容.