OkHttp:与http://example.com/的连接泄露了。你忘记关闭一个响应机构了吗?

时间:2016-11-17 17:17:42

标签: 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 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);
  }
}

2 个答案:

答案 0 :(得分:2)

结果我的拦截器被窃听:

return chain.proceed(request);

应该是:

return response;

答案 1 :(得分:0)

我们可以在 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
                }