I'm having a warning message constantly, despite my code seems to be good. The message is:
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)
I'm working with Java 8. I've tried with the traditional try-catch
and with this approach (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());
}
}
In fact, the first if line is never called, I always have an exception, so I cannot understand why the response/body is not closed by the try-with-resources block
I've tried this option as well, but it didn't work either:
try (Response response = client.newCall(request).execute()) { ... }
EDIT
I've reduced my code, and I'm still having the same error, this is even weirder:
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());
}
}
EDIT 2:
I've tried with the traditional try-catch
but I'm still having the same issue:
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();
}
}
}
As per Response.close()
javadoc:
It is an error to close a response that is not eligible for a body. This includes the responses returned from
cacheResponse
,networkResponse
, andpriorResponse()
.
Perhaps your code should look like below, as per Github comment:
while (repeatRequest) {
Call call = client.newCall(request);
Response response = call.execute();
try (ResponseBody body = response.body()) {
...
}
}