尽管我的代码看起来很不错,但我一直收到警告信息。这个消息是:
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
):
我使用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();
}
}
}