OkHttp: A connection to http://example.com/ was leaked. Did you forget to close a response body?

断了今生、忘了曾经 提交于 2019-12-11 05:44:42

问题


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;
    }
  }

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);
  }
}

回答1:


Turns out my interceptor was bugged:

return chain.proceed(request);

should be:

return response;


来源:https://stackoverflow.com/questions/40661172/okhttp-a-connection-to-http-example-com-was-leaked-did-you-forget-to-close

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!