java我是这样写的,但是仍然得到了错误“到XXX的连接被泄露了。你忘记关闭响应体了吗?”
我不知道如何避免它,我已经关闭了响应体
有人能帮我解决这个问题吗
我的代码:
public String getPageFromServer(String activityKey) throws Exception {
String address = pageServerHolder.getServerAddressRandom();
String url = MessageFormat.format(URL, address, activityKey);
log.debug("=============== url [{}] ================", url);
OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.SECONDS).callTimeout(1, TimeUnit.SECONDS).build();
final Request request = new Request.Builder().url(url).get().build();
Response response = client.newCall(request).execute();
try (ResponseBody body = response.body()) {
if (response.isSuccessful() && null != body) {
String bodyString = body.string();
if (StringUtils.isNotBlank(bodyString)) {
body.close();
return bodyString;
}
}
}
throw new RuntimeException(MessageFormat.format("获取活动页信息异常,url [{0}], response.code [{1}],response.message [{2}] ", url, response.code(), response.message()));
}
# 1 楼答案
你的问题是
Response
没有关闭。你的代码应该是这样的:我不确定你是否需要关闭^{。关闭
response
可能会解决这个问题。然而,冗余关闭几乎没有什么害处看看这里的例子:https://square.github.io/okhttp/
# 2 楼答案
我想知道这只是来自okhttp客户端的一个错误。即使是
try resource
语法也无法解决警告问题# 3 楼答案
ResponseBody实现了可关闭的接口。您正在try块的资源部分创建responsebook,当您离开try块时,它将为您关闭
你的“body.close()”不应该在那里