59

我试图让 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(...)调用中获取状态码和响应体?提前致谢!

4

5 回答 5

70

不要将处理程序提供给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,代码可能看起来不同。

于 2012-12-24T18:39:59.543 回答
36

您可以避免使用 BasicResponseHandler,但使用 HttpResponse 本身来获取状态和响应作为字符串。

HttpResponse response = httpClient.execute(get);

// Getting the status code.
int statusCode = response.getStatusLine().getStatusCode();

// Getting the response body.
String responseBody = EntityUtils.toString(response.getEntity());
于 2016-01-12T10:12:08.400 回答
15

如果状态不是 2xx,则 BasicResponseHandler 抛出。查看它的javadoc

这是我的做法:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

或者您也可以从 BasicResponseHandler 源开始编写一个 ResponseHandler,当状态不是 2xx 时不会抛出。

于 2014-10-09T18:16:46.873 回答
5

流畅的外观 API:

Response response = Request.Get(uri)
        .connectTimeout(MILLIS_ONE_SECOND)
        .socketTimeout(MILLIS_ONE_SECOND)
        .execute();
HttpResponse httpResponse = response.returnResponse();
StatusLine statusLine = httpResponse.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
    // 响应内容编码自适应?(好像没那么智能)
    String responseContent = EntityUtils.toString(
            httpResponse.getEntity(), StandardCharsets.UTF_8.name());
}
于 2016-11-27T16:26:43.510 回答
1

如果您使用的是 Spring

return new ResponseEntity<String>("your response", HttpStatus.ACCEPTED);
于 2017-03-15T15:22:18.103 回答