Lam
Lam

Reputation: 543

OkHttp 3 IllegalStateException

I customize an interceptor to refresh token when it's expired. When I get response body to detect if the token's expired, it throw java.lang.IllegalStateException: closed.

Here is my code with OkHttp 3

@Override
public Response intercept(Chain chain) throws IOException {
    Request original = chain.request();
    Request.Builder requestBuilder = original.newBuilder()
            .header("Content-Type", "application/json")
            .header(Constants.TAG_AUTHORIZATION, "Bearer " + token)
            .method(original.method(), original.body());


    Request request = requestBuilder.build();
    Response response = chain.proceed(request);
    if (response.code() == 200) {
        String json = response.body().string();
        try {
            JSONObject obj = new JSONObject(json);
            int code = obj.getInt(Constants.TAG_CODE);
            if (code == Constants.REQUEST_CODE_TOKEN_EXPIRED) {
                Response r = makeTokenRefreshCall(request, chain);
                return r;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return response;
}

Please help me!

Upvotes: 2

Views: 3365

Answers (2)

Lam
Lam

Reputation: 543

Finally, I found a solution to read response body without exception

 ResponseBody body = response.body();
 BufferedSource source = body.source();
 if (source.request(1024)) throw new IOException("Body too long!");
 Buffer bufferedCopy = source.buffer().clone();
 ResponseBody newBody = ResponseBody.create(body.contentType(), body.contentLength(), bufferedCopy);
 String responseBodyString = newBody.string();

Upvotes: 3

Jesse Wilson
Jesse Wilson

Reputation: 40623

You're not allowed to consume the response body in an interceptor. If you'd like to work around this, use Response.peekBody() which makes a copy that you are allowed to read.

Upvotes: 4

Related Questions