Vil*_*lat 16 java try-with-resources
尽管我的代码看起来不错,但我不断收到警告消息。消息是:
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)
Run Code Online (Sandbox Code Playgroud)
我正在使用 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());
}
}
Run Code Online (Sandbox Code Playgroud)
事实上,第一个if行从来没有被调用过,我总是有一个例外,所以我不明白为什么 try-with-resources 块没有关闭响应/正文
我也试过这个选项,但它也不起作用:
try (Response response = client.newCall(request).execute()) { ... }
Run Code Online (Sandbox Code Playgroud)
编辑
我已经减少了我的代码,但我仍然有同样的错误,这更奇怪:
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());
}
}
Run Code Online (Sandbox Code Playgroud)
编辑 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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
关闭不符合正文的响应是错误的。这包括从返回的响应
cacheResponse,networkResponse和priorResponse()。
根据Github 评论,也许您的代码应该如下所示:
while (repeatRequest) {
Call call = client.newCall(request);
Response response = call.execute();
try (ResponseBody body = response.body()) {
...
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11928 次 |
| 最近记录: |