有没有一种方法可以防止Apache CloseableHttpClient抛出HttpResponseException?

时间:2020-02-22 15:04:22

标签: java apache-httpclient-4.x apache-httpcomponents web-api-testing

我正在使用Apache HttpComponents(4.5.11)测试Web API。

对于否定测试(例如,发送错误的请求),我也想检查响应正文,但是CloseableHttpClient会使用响应的状态代码抛出HttpResponseException而不是返回实际响应。 有什么方法可以防止这种情况,还是我应该切换到另一个库(例如RestAssured)?

这是我的做法:

try (CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request)) {
     ResponseHandler<String> handler = new BasicResponseHandler();
     String body = handler.handleResponse(response);
     //Deserialize and perform response assertions..
} catch(HttpResponseException e){
    //Exception is caught here..
}

pom.xml依赖项:

    <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.11</version>
    </dependency>

1 个答案:

答案 0 :(得分:1)

我不确定是否理解问题。没有什么可以阻止您获取状态代码并直接从响应对象读取响应内容。

try (CloseableHttpClient httpClient = HttpClients.createDefault();
     CloseableHttpResponse response = httpClient.execute(request)) {
    int statusCode = response.getStatusLine().getStatusCode();
    final HttpEntity entity = response.getEntity();
    if (entity != null) {
        try (InputStream inputStream = entity.getContent()) {
            // Do something useful with the response
        }
    }
}