首页 > 解决方案 > 使用 java 控制何时关闭 OkHttpClient3

问题描述

当我设置 okhttpClient3 时,我正在发送如下获取请求:

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

我看到当我尝试返回字符串响应时,我得到客户端已关闭。当客户将要关闭时,我该如何管理?

标签: javaokhttp

解决方案


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

如果此响应已传递给 {@link Callback#onResponse} 或从 {@link Call#execute()} 返回,则返回非空值。响应正文必须是 {@linkplain ResponseBody closed} 并且只能使用一次。您可以通过先将其保存在变量中然后使用此变量来避免这种情况,例如

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()) {
...
}

推荐阅读