Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IllegalStateException: response is not eligible for a body and must not be closed

Tags:

okhttp

sometimes we get this exception handling Response. It seems that Response has a null body.

The code is something like:

try (Response response = client.newCall(request).execute()) {
  // do stuff with the response
} catch (Exception e) {
  log.error("Something wrong", e);
}

The exception is raised on the close() method automatically called on the Response, after the do stuff with response block went executed.

Stack trace:

java.lang.IllegalStateException: response is not eligible for a body and must not be closed
    at okhttp3.Response.close(Response.java:281)

Are we missing something?
Thanks.

like image 502
ndr_brt Avatar asked Sep 01 '25 10:09

ndr_brt


2 Answers

I think u can invoke response.body.close() which is the same as response.close(), and check body is null or not before close.

        ResponseBody responseBody = null;
        try {
            Response response = client.newCall(request).execute();
            responseBody = response.body();
            // do stuff with the response
        } catch (Exception e) {
            log.error("Something wrong", e);
        } finally {
            if (responseBody != null) {
                responseBody.close();
            }
        }
like image 194
Jerry Wu Avatar answered Sep 13 '25 14:09

Jerry Wu


Since the Try with Resources works with Auto-closable (ie classes implement the Closable interface, it tries to call close automatically after the block.

Now the spec for Response close() method, does specify the method would throw and exception in certain cases.

It is an error to close a response that is not eligible for a body. This includes the responses returned from {@link #cacheResponse}, {@link #networkResponse}, and {@link priorResponse()}.

Source: https://github.com/square/okhttp/blob/master/okhttp/src/main/java/okhttp3/Response.java

So, it is 'expected' you can just log the details and continue if it is expected. OR handle appropriately (eg: retry) if it is not expected..

like image 42
srikanth Nutigattu Avatar answered Sep 13 '25 14:09

srikanth Nutigattu