2017-07-03 36 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異常 –