java - 使用 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;
}
我看到当我尝试返回字符串响应时,我得到客户端已关闭。当客户将要关闭时,我该如何管理?
解决方案
通过执行两次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()) {
...
}
推荐阅读
- php - PHP联系页面设置
- javascript - 是否可以从网站运行不和谐的机器人命令
- javascript - 如何使用 Node js 在单个 API 调用中传递两个请求 - Cloudant
- spring-boot - java.lang.OutOfMemoryError:Java 堆空间 Hibernate entityIsPersistent
- facebook-graph-api - Instagram 视频发布时的图形 API 问题 - 媒体上传失败,错误代码为 2207026"
- r - plot_ly:可以为 scatter3D 绘图设置主题吗?
- javascript - 如何在 onSubmit 后使用表单显示内容的时间超过一秒钟
- msp430 - 使用 MSP430FR5969 MCU 从 TMP117 传感器读取温度值
- stored-procedures - 如何将程序的使用权限授予广泛的角色组?
- api - QuickBooks online 如何确定 ExpenseAccountRef.value?我是否需要查询一个 ACCOUNT 对象来确定该值?