2. 概述
本快速教程将演示如何 使用 HttpClient 获取并验证 HTTP 响应的状态码。
若想深入探索 HttpClient 的其他实用功能,可参考 **主要 HttpClient 教程**。
3. 从 HTTP 响应中提取状态码
执行 HTTP 请求后,我们将获得 org.apache.hc.client5.http.impl.classic.ClosableHttpResponse
实例,通过该实例可直接访问状态码:
response.getCode()
利用此方法,可验证服务器返回的状态码是否符合预期:
@Test
public final void givenGetRequestExecuted_whenAnalyzingTheResponse_thenCorrectStatusCode() throws IOException {
final HttpGet request = new HttpGet(SAMPLE_URL);
try (CloseableHttpClient client = HttpClientBuilder.create().build();
CloseableHttpResponse response = (CloseableHttpResponse) client
.execute(request, new CustomHttpClientResponseHandler())) {
assertThat(response.getCode(), equalTo(HttpStatus.SC_OK));
}
}
✅ 注意:我们使用了库中预定义的状态码常量(通过 org.apache.hc.core5.http.HttpStatus
提供)。
4. 总结
这个简单示例展示了 使用 Apache HttpClient 获取和处理状态码 的方法。
所有示例代码的实现 可在 我的 GitHub 项目 中找到。该项目基于 Eclipse 构建,可直接导入运行。