【问题标题】:After reading raw response through interceptor, retrofit is not receiving respose in call body通过拦截器读取原始响应后,改造未在调用正文中接收响应
【发布时间】:2017-07-03 19:47:09
【问题描述】:

如果我在通过拦截器返回原始响应之前添加一个拦截器来读取原始响应,我会在改造调用中失败 我的拦截器代码:

 Response originalResponse = chain.proceed(builder.build());

 String rawJson = originalResponse.body().string();
 try {
      JSONObject jsonObject = new JSONObject(rawJson);
      if (jsonObject.has("respCode")) {
            if (jsonObject.getString("respCode").equals("E")) {
                context.getSharedPreferences(AppConstants.PREF_NAME, Context.MODE_PRIVATE).edit()
                .putBoolean(AppConstants.IS_LOGGED_IN_KEY, false)
                .apply();
                context.startActivity(new Intent(context, LoginActivity.class));
             }
         }
   } catch (JSONException e) {
          e.printStackTrace();
   }
   return originalResponse;

其中没有编译错误。 没有这个 try-catch 块,一切正常。

任何建议都会有所帮助

【问题讨论】:

    标签: android retrofit retrofit2 okhttp3


    【解决方案1】:

    您可以在HttpLoggingInterceptor 中看到示例

    ResponseBody responseBody = originalResponse.body();
    BufferedSource source = responseBody.source();
    source.request(Long.MAX_VALUE); // Buffer the entire body.
    Buffer buffer = source.buffer();
    String rawJson = buffer.clone().readString(Charset.forName("UTF-8"));
    

    【讨论】:

      猜你喜欢
      • 2016-05-02
      • 2012-06-22
      • 1970-01-01
      • 2015-12-28
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多