Michel Jung
Michel Jung

Reputation: 3286

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

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

Upvotes: 2

Views: 10651

Answers (2)

Mori
Mori

Reputation: 4641

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
                }

Upvotes: 0

Michel Jung
Michel Jung

Reputation: 3286

Turns out my interceptor was bugged:

return chain.proceed(request);

should be:

return response;

Upvotes: 2

Related Questions