OkHttp:与 http://example.com/ 的连接已泄露。您是否忘记关闭响应主体?

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

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

我们可以在 Kotlin 中使用这种方式

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
                }