gpt4 book ai didi

java - 有没有办法防止 Apache CloseableHttpClient 抛出 HttpResponseException?

转载 作者:行者123 更新时间:2023-12-02 08:58:20 25 4
gpt4 key购买 nike

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

最佳答案

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

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
}
}
}

关于java - 有没有办法防止 Apache CloseableHttpClient 抛出 HttpResponseException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60353480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com