本文介绍了OkHttp:与http://example.com/的连接已泄漏.您是否忘记了关闭响应主体?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
OkHttp v3.4.1的错误消息已经被讨论过几次了,每次我读到它时,人们并没有关闭响应主体:
This error message of OkHttp v3.4.1 has already been discussed a few times, and each time I read about it, people were not closing the response body:
WARNING: A connection to http://www.example.com/ was leaked. Did you forget to close a response body?
但是我的代码是这样的:
But my code reads like this:
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拦截器,但是我看不到它怎么会引起问题:
So responseBody.close()
is always called. How come I get the above error? I configured a custom JWT interceptor, but I don't see how it could cause the problem:
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);
}
}
推荐答案
原来我的拦截器有问题:
Turns out my interceptor was bugged:
return chain.proceed(request);
应为:
return response;
这篇关于OkHttp:与http://example.com/的连接已泄漏.您是否忘记了关闭响应主体?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!