如何获取返回状态代码和响应正文的 HttpClient?

2022-08-31 16:19:23

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

不幸的是,我只能让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库,我如何从同一个客户端获取状态代码和响应正文。execute(...) 调用?提前致谢!


答案 1

不要向 提供处理程序。execute

获取对象,使用处理程序获取正文并直接从中获取状态代码HttpResponse

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,代码可能看起来不同。


答案 2

您可以避免使用 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());

推荐