gpt4 book ai didi

java - 使用java控制何时关闭HttpClient s3

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

当我设置 okhttpClient3 时,我发送一个如下的 get 请求:

public String sendGetRequest(String url, HashMap<String, String> headersMap) throws Exception {

Headers headers = addHeaders(headersMap);
Request request = new Request.Builder()
.url(url).headers(headers).build();
try{
Response response =httpClient.newCall(request).execute();
LOG.info(String.format("Response data is: =[%s]", response.body().string()));
return response.body().string();
}catch(Exception e){
LOG.error(String.format("Request failed=[%s]",e.getMessage()));

}finally {
httpClient.connectionPool().evictAll();
}

return null;
}

我发现当我尝试返回字符串响应时,我发现客户端已关闭。当客户即将关闭时我该如何管理?

最佳答案

通过执行两次 response.body(),您尝试使用请求正文两次:一次在日志记录 LOG.info(String.format("Response data is: =[% s]", response.body().string())); 并在 return 语句中返回 response.body().string();。根据文档,它只能消耗一次:

Returns a non-null value if this response was passed to {@link Callback#onResponse} or returned from {@link Call#execute()}. Response bodies must be {@linkplain ResponseBody closed} and may be consumed only once. You can avoid this by saving it in a variable first and then use this variable, e.g.

final String requestBody = response.body().string();
LOG.info(String.format("Response data is: =[%s]", requestBody));
return requestBody;

您还可以用 try-with-resources 风格替换 try-catch,即

try (Response response = httpClient.newCall(request).execute()) {
...
}

关于java - 使用java控制何时关闭HttpClient s3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61437302/

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