java - 如何让 HttpClient 返回状态码和响应正文?

标签 java http apache-httpclient-4.x

我正在尝试让 Apache HttpClient 触发 HTTP 请求,然后显示 HTTP 响应代码(200、404、500 等)以及 HTTP 响应正文(文本字符串)。重要的是要注意我使用的是 v4.2.2 因为大多数 HttpClient 示例来自 v.3.x.x 并且 API 从版本 3 到版本 4 发生了很大变化.

不幸的是,我只能让 HttpClient 返回状态代码响应正文(但不能同时返回两者)。

这是我所拥有的:

// Getting the status code.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
HttpResponse resp = client.execute(httpGet);

int statusCode = resp.getStatusLine().getStatusCode();


// Getting the response body.
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://whatever.blah.com");
ResponseHandler<String> handler = new BasicResponseHandler();

String body = client.execute(httpGet, handler);

所以我问:使用 v4.2.2 库,如何从同一个 client.execute(...) 获取状态码和响应体 打电话? 提前致谢!

最佳答案

不要将处理程序提供给执行

获取HttpResponse对象,使用handler获取body,直接从中获取状态码

try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
    final HttpGet httpGet = new HttpGet(GET_URL);

    try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
        StatusLine statusLine = response.getStatusLine();
        System.out.println(statusLine.getStatusCode() + " " + statusLine.getReasonPhrase());
        String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
        System.out.println("Response body: " + responseBody);
    }
}

对于快速单次调用,fluent API 很有用:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();

对于旧版本的 java 或 httpcomponents,代码可能看起来不同。

关于java - 如何让 HttpClient 返回状态码和响应正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14024625/

相关文章:

java - Twitter,获取过去 24 小时的所有推文

java - 删除文本文件中的多余行

java - 带有 chromedriver 的 Selenium 根据 "headless"参数给出不同的结果

java - websphere下如何找到运行时应用程序安装的目录

javascript - 在 Protractor 测试中无法使用户 session 保持事件状态

http - Camel : how to predict HTTP charchester encoding when doing conversion

java - 使用 HttpClient 写入正文请求

http - 为什么 Go http.Client 中的 POST 请求不遵循 301 重定向?

http - Camel : outgoing connections limit for http component

java - 使用池连接管理器时,为什么我的 HTTPClient 连接耗尽?