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

标签 java okhttp

当我设置 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/

相关文章:

java - 用于 http 请求和响应日志记录的 HttpLoggingInterceptor

java - 亚马逊波利 API

java - Hadoop MapReduce 使用键对归约输出进行排序

java - Maven 更新项目后项目结构发生了变化,源文件夹的包含和排除模式也发生了变化

java - BadCredentialsException 是 spring-security

java - StringBuilders 是否应该始终用于字符串操作?

java - Hibernate:如何将此标准重写为 HQL?

android - 启用缩小的 Moshi 抛出异常 "Unable to create converter"

java - Android okHttp 重试策略

java - 是否可以为 https 禁用 ssl?