【发布时间】:2019-12-07 04:05:30
【问题描述】:
尽管我的代码看起来不错,但我不断收到警告消息。消息是:
WARNING: A connection to http://someurl.com was leaked. Did you forget to close a response body?
java.lang.Throwable: response.body().close()
at okhttp3.internal.platform.Platform.getStackTraceForCloseable(Platform.java:148)
at okhttp3.RealCall.captureCallStackTrace(RealCall.java:89)
at okhttp3.RealCall.execute(RealCall.java:73)
at com.example.HTTPSClientReferenceRate.runClient(HTTPSClientReferenceRate.java:78)
at com.example.HTTPSClientReferenceRate.main(HTTPSClientReferenceRate.java:137)
我正在使用 Java 8。我尝试过使用传统的 try-catch 和这种方法 (try-with-resources):
boolean repeatRequest = true;
while(repeatRequest) {
Call call = client.newCall(request);
try (Response response = call.execute()){
if (!response.isSuccessful()) {
log.error("Error with the response: " + response.message());
continue;
}
ResponseBody body = response.body();
if (body == null){
log.error("Error when getting body from the response: " + response.message());
continue;
}
BufferedReader br = new BufferedReader(body.charStream());
//...DATA HANDLING
} catch (Exception e) {
log.error("Error Connecting to the stream. Retrying... Error message: " + e.getMessage());
}
}
事实上,第一行 if 从来没有被调用过,我总是有一个异常,所以我不明白为什么响应/正文没有被 try-with-resources 块关闭
我也试过这个选项,但也没有用:
try (Response response = client.newCall(request).execute()) { ... }
编辑
我已经减少了我的代码,我仍然有同样的错误,这更奇怪:
boolean repeatRequest = true;
while(repeatRequest) {
Call call = client.newCall(request);
try (Response response = call.execute()){
//NOTHING
} catch (Exception e) {
log.error("Error Connecting to the stream. Retrying... Error message: " + e.getMessage());
}
}
编辑 2:
我已经尝试过使用传统的try-catch,但我仍然遇到同样的问题:
boolean repeatRequest = true;
while(repeatRequest) {
Call call = client.newCall(request);
Response response = null;
try {
response = call.execute();
try (ResponseBody body = response.body()) {
//Nothing...
}
} catch (Exception e) {
log.error("Error Connecting to the stream. Retrying... Error message: " + e.getMessage());
} finally {
if (response != null){
response.close();
}
}
}
【问题讨论】:
-
试试这个:try (Response response = client.newCall(request).execute()) {
-
@btreport 我之前试过了,但运气不好,我会把它添加到我的帖子描述中。
-
你在使用哪个版本的java?
-
@ErHarshRathore 我正在使用 Java 8
-
据我所知,java 8 无法读取这个 try (Response response = call.execute()){} 相反,您应该像 Response response 一样分别尝试声明和定义;尝试(响应 = call.execute())