我正在使用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>
答案 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
}
}
}