Java OkHttp:到的连接http://example.com/ 被泄露了。你忘了关闭一个响应机构了吗?
OkHttp v3.4.1的这个错误消息已经讨论过几次了,每次我读到它时,人们都没有关闭响应主体:Java OkHttp:到的连接http://example.com/ 被泄露了。你忘了关闭一个响应机构了吗?,java,okhttp3,Java,Okhttp3,OkHttp v3.4.1的这个错误消息已经讨论过几次了,每次我读到它时,人们都没有关闭响应主体: WARNING: A connection to http://www.example.com/ was leaked. Did you forget to close a response body? 但我的代码是这样的: private String executeRequest(Request request) throws IOException { Response r
WARNING: A connection to http://www.example.com/ was leaked. Did you forget to close a response body?
但我的代码是这样的:
private String executeRequest(Request request) throws IOException {
Response response = httpClient.newCall(request).execute();
try (ResponseBody responseBody = response.body()) {
String string = responseBody.string();
logger.debug("Result: {}", string);
return string;
}
}
因此总是调用responseBody.close()
我怎么会出现上述错误?我配置了一个自定义JWT拦截器,但我不知道它是如何导致问题的:
public class JwtInterceptor implements Interceptor {
private String jwt;
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (jwt != null) {
request = request.newBuilder()
.addHeader("Authorization", "Bearer " + jwt)
.build();
}
Response response = chain.proceed(request);
String jwt = response.header("jwt");
if (jwt != null) {
this.jwt = jwt;
}
return chain.proceed(request);
}
}
原来我的拦截器被窃听了:
return chain.proceed(request);
应该是:
return response;
我们可以在科特林用这种方法
try {
val req: Request = Request.Builder().url(url).get().build()
val client = OkHttpClient()
val resp: Response = client.newCall(req).execute()
val code: Int = resp.code() // can be any value
body= resp.body()
if (code == 200) {
body?.close() // I close it explicitly
}
在您的示例中,
responseBody.close()
在哪里被调用?我只能说,response.close()
从未被调用过^^^^^^^请尝试使用resourcesCan,您提供了一个?警告记录在哪里?它期望响应为返回类型。它是如何工作的?公共响应拦截(Chain Chain)抛出IOException{谢谢@chetan.sankhala,应该是返回响应
。我更新了答案。