2

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);
  }
}
Michel Jung
  • 2,966
  • 6
  • 31
  • 51

2 Answers2

2

Turns out my interceptor was bugged:

return chain.proceed(request);

should be:

return response;
Michel Jung
  • 2,966
  • 6
  • 31
  • 51
0

We can use this way in 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
                }
Mori
  • 2,653
  • 18
  • 24