2017-07-03 56 views
1

我定制了一个拦截器,以便在其过期时刷新令牌。当我得到response body来检测token是否过期时,它会抛出java.lang.IllegalStateException:closed。OkHttp 3 IllegalStateException

这里是我的代码以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; 
} 

请帮帮我!

+0

什么是例外?显示logcat – matrix

+0

@matrix异常不是在拦截()中抛出,而是在我的RxJava onError()方法中。 –

回答

1

您不允许在拦截器中使用响应主体。如果您想要解决此问题,请使用Response.peekBody(),它会复制您允许阅读的副本。

+0

peekBody也会抛出IllegalStateException –

1

最后,我发现了一个解决方案,读取响应体无一例外

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(); 
+0

这会导致IllegalStateException异常 –