与 (...) 的连接已泄露。您是否忘记关闭响应正文?
2022-09-02 10:46:33
我不断收到警告消息,尽管我的代码似乎很好。消息是:
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());
}
}
事实上,如果第一行从未被调用,我总是有一个例外,所以我无法理解为什么响应/正文没有被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();
}
}
}