示例#1
0
  private Response getResponseWithInterceptorChain() throws IOException {
    // Build a full stack of interceptors.
    List<Interceptor> interceptors = new ArrayList<>();
    interceptors.addAll(client.interceptors());
    interceptors.add(retryAndFollowUpInterceptor);
    interceptors.add(new BridgeInterceptor(client.cookieJar()));
    interceptors.add(new CacheInterceptor(client.internalCache()));
    interceptors.add(new ConnectInterceptor(client));
    if (!retryAndFollowUpInterceptor.isForWebSocket()) {
      interceptors.addAll(client.networkInterceptors());
    }
    interceptors.add(new CallServerInterceptor(retryAndFollowUpInterceptor.isForWebSocket()));

    Interceptor.Chain chain =
        new RealInterceptorChain(interceptors, null, null, null, 0, originalRequest);
    return chain.proceed(originalRequest);
  }
示例#2
0
 /**
  * 包装OkHttpClient,用于下载文件的回调
  *
  * @param client 待包装的OkHttpClient
  * @param progressListener 进度回调接口
  * @return 包装后的OkHttpClient,使用clone方法返回
  */
 public static OkHttpClient addProgressResponseListener(
     OkHttpClient client, final ProgressListener progressListener) {
   // 克隆
   OkHttpClient clone = client.newBuilder().build();
   // 增加拦截器
   clone
       .networkInterceptors()
       .add(
           new Interceptor() {
             @Override
             public Response intercept(Chain chain) throws IOException {
               // 拦截
               Response originalResponse = chain.proceed(chain.request());
               // 包装响应体并返回
               return originalResponse
                   .newBuilder()
                   .body(new ProgressResponseBody(originalResponse.body(), progressListener))
                   .build();
             }
           });
   return clone;
 }