OKHttp throwing an illegal state exception when I try to log the network response

jenkins java.lang.illegalstateexception: closed
okhttp log response body
okhttp interceptor log
okhttp response
fatal exception: okhttp dispatcher
okhttp close response
clone okhttp response
okhttp response body

I put the following interceptor on my OkHttp client:

httpClient.addInterceptor(new Interceptor() {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Response response = chain.proceed(chain.request());
        Log.d("Response", response.body().string());
        return response;
    }
    });

However, this isn't playing nice with Retrofit 2. It seems that you can only read the stream from the response once and that might be what is causing the exception. I'm thinking retrofit is trying to parse the stream which the log already parsed. How then do I get my hands on the response? I'm currently trying to debug a very nasty and strange malformed json exception.

This is the exception stack trace:

07 - 28 10: 58: 21.575 22401 - 22529 / REDACTED E / AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher
    Process: REDACTED, PID: 22401
    java.lang.IllegalStateException: closed
    at okhttp3.internal.http.Http1xStream$FixedLengthSource.read(Http1xStream.java: 378)
    at okio.Buffer.writeAll(Buffer.java: 956)
    at okio.RealBufferedSource.readByteArray(RealBufferedSource.java: 92)
    at okhttp3.ResponseBody.bytes(ResponseBody.java: 83)
    at okhttp3.ResponseBody.string(ResponseBody.java: 109)
    at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 90)
    at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
    at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
    at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
    at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
    at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
    at REDACTED.ServiceGenerator$2.intercept(ServiceGenerator.java: 89)
    at okhttp3.RealCall$ApplicationInterceptorChain.proceed(RealCall.java: 187)
    at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java: 160)
    at okhttp3.RealCall.access$100(RealCall.java: 30)
    at okhttp3.RealCall$AsyncCall.execute(RealCall.java: 127)
    at okhttp3.internal.NamedRunnable.run(NamedRunnable.java: 32)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java: 1112)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java: 587)
    at java.lang.Thread.run(Thread.java: 841)

I see that there are multiple interceptors in the stack but I only ever explicitly add the one, which is the on that is throwing the exception.

You are consuming the response body in the interceptor, so you're going to want to create a new response:

@Override public Response intercept(Chain chain) throws IOException {
  Response response = chain.proceed(chain.request());
  ResponseBody body = response.body();
  String bodyString = body.string();
  MediaType contentType = body.contentType();
  Log.d("Response", bodyString);
  return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build();
}

You may also want to check out the logging interceptor in OkHttp's repo: https://github.com/square/okhttp/tree/master/okhttp-logging-interceptor

java.lang.IllegalStateException: closed when trying to access , IllegalStateException: closed at com.squareup.okhttp.internal.http. when trying to access response in onResponse(Response response) #1240 so OkHttp doesn't store it in memory, it reads it as a stream from network when you need it. It won't throw any exception if you do this. Sign in to comment. java – OKHttp throwing an illegal state exception when I try to log the network response . Posted by: admin May 11, 2020 Leave a comment. Questions:

Do not call response body more than once, since it is read as a stream and not stored in memory.

Maybe you are calling response.body().string() more than once because response body can be huge so OkHttp doesn’t store it in memory, it reads it as a stream from network when you need it.

When you read body as a string() OkHttp downloads response body and returns it to you without keeping reference to the string, it can’t be downloaded twice without new request.

https://github.com/square/okhttp/issues/1240

okhttp3.ResponseBody java code examples, Builder() .url(url) .build(); try (Response response = client. in OkHttp: https://​github.com/square/okhttp/issues/3111 if ((response.code() == 307) networkResponse() != null ? throw new IllegalStateException(format("Missing HTTP header 'Location' in contentType() != null) { logger.log("Content-Type: " + requestBody. Because response body can be huge so OkHttp doesn’t store it in memory, it reads it as a stream from network when you need it. When you read body as a string() OkHttp downloads response body and returns it to you without keeping reference to the string, it can’t be downloaded twice without new request.


I also got this exception due to trying to convert response body 2X. First i logged the response.body().string() & then again i passed the same to a method. Which was causing the exception. Check if the response body is converted to string more than once.

okhttp3.Request$Builder java code examples, Sending http request using okhttp Builder() .url(url) .post(body) .build(); try (​Response response = client. catch (IOException e) { throw new IllegalStateException("Failed contacting Datadog networkResponse() != null ? remoteAddress)); } catch (IOException e) { LOG.error("Could not fetch HTTP resource at " + url, e);. The log shows my REST reader getting an IllegalStateException when trying to read from an HTTP connection that has been closed (not by me). I think it should throw an IOException instead. This is with the okhttp 2.0 master branch. java.l

The error is weird but the the first problem I see is that you are using OKHTTP3 and trying to add a builder to the already created client.

The OkHttpClient is immutable now and you will have to add the interceptors directly to the OkHttpClient.Builder by calling addInterceptor method on the builder.

For more clarity on how to do this see this Github Issue. I think this should solve your problem.

FATAL EXCEPTION: OkHttp Dispatcher, I'm using the OkHttp library in my android app to make web requests to a weather API. I've already added INTERNET permissions in my manifest too. throws IOException { try { Log.v(TAG, response.body().string()); String jsonData = response.body().string(); if IllegalStateException: closed at okio. i get FATAL EXCEPTION: OkHttp Dispatcher Process: com.dyb_app, PID: 20703 java.lang.IllegalStateException: closed at okio.RealBufferedSink.write(RealBufferedSink.java:39)

Response body can be huge so OkHttp doesn’t store it in memory, it reads it as a stream from network when you need it.

When you read body as a string() OkHttp downloads response body and returns it to you without keeping reference to the string, it can’t be downloaded twice without new request.

Changelog 2x - OkHttp, The logging-interceptor subproject offers simple request and response logging. Fix: Don't throw when converting an HttpUrl to a java.net. Fix: Don't crash with an IllegalStateException if an HTTP/2 or SPDY write fails, leaving the Fix: When a network interceptor mutates a request, that change is now Please try it out! Which has a nice exception. The problem here is that the server is seemingly closing your socket without sending an appropriate response e.g. 503. I don't think it is appropriate to make the exceptions for badly behaved servers effectively part of the published API. For expected failure modes (5xx, 4xx, timeout exceptions) they effectively are.

Diff - platform/external/okhttp - Git at Google, The `logging-interceptor` subproject offers + simple request and response logging. + + * Fix: Don't throw when converting an `HttpUrl` to a `java.net.URI`. Network. - public static OkUrlFactory createHttpOkUrlFactory(Proxy proxy) + try { + url.uri(); + fail(); + } catch (IllegalStateException expected) { + // Possibly a bug in  Clone via HTTPS Clone with Git or checkout with SVN using the repository’s web address.

How to handle RESTful web Services using Retrofit, OkHttp, Gson , These days almost every Android app connects to internet to get/send data. Gson will check the JSON for all names we specify and try to find one to // map it to retryOnConnectionFailure(false) // Log requests and responses. ApiResponse::class.java) { throw IllegalArgumentException("type must be a  throw privilegedActionException.getException() will attempt to throw a null value. There are 19 such places in Android N; sadly, this is one of them. :-( I plan to take appropriate measures to make vendors aware of this issue and the patch. 👍

Java Code Examples com.squareup.okhttp.Interceptor, nanoTime(); Log.e("Log", String.format("Received response for %s in 1) { throw new IllegalStateException("network interceptor " + localInterceptor1 + " must OkHttpClient okHttpClient = new OkHttpClient(); // TODO try wiping cache to see  02: The Exception Code B053: The CRC (cyclic redundancy check). Following the Function Code is the Exception Code. The exception code gives an indication of the nature of the problem. The possible codes are shown in the table below. The exception code shown above 02 is an indication that coil #1186 is an illegal address in the slave. This coil

Comments
  • github.com/square/okhttp/issues/1240
  • @Eric I did exactly as you did and keep getting the same error. I did comment the bodyString line (so the body.string() wont be called) and put a random String as the body. Any ideais?
  • if (response.code() == HTTP_OK) { Context context = AutoAtendimentoApplication.getContext(); String request = response.request().url().toString(); ResponseBody body = response.body(); String bodyString = body.string(); okhttp3.MediaType contentType = body.contentType(); CacheHelper.setCache(context, request, bodyString); return response.newBuilder().body(ResponseBody.create(contentType, bodyString)).build(); }
  • @FelipeCastilhos are you getting java.lang.IllegalStateException: closed? there could be a consumer of your response at another point. probably check your detailed stack trace.
  • I did a clean and rebuild and everything work it out. Thanks for the reply!
  • (This post does not seem to provide a quality answer to the question. Please either edit your answer and improve it, or just post it as a comment to the question).
  • Thanks for your response. The variable you're seeing is actually the builder but is poorly named. Also, I figured out my problem. You can look in this class to see how to intercept a response and not effect its state (involves getting the connection itself): github.com/square/okhttp/blob/master/okhttp-logging-interceptor/…