Java 类com.squareup.okhttp.Interceptor 实例源码

项目:AndroidTvBoilerplate    文件:AndroidTvBoilerplateService.java   
public static AndroidTvBoilerplateService newVineyardService() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            // Catch unauthorised error
            return response;
        }
    });

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AndroidTvBoilerplateService.ENDPOINT)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    return retrofit.create(AndroidTvBoilerplateService.class);
}
项目:NewsMe    文件:ProgressHelper.java   
/**
 * 包装OkHttpClient,用于下载文件的回调
 * @param client 待包装的OkHttpClient
 * @param progressListener 进度回调接口
 * @return 包装后的OkHttpClient,使用clone方法返回
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressResponseListener progressListener){
    //克隆
    OkHttpClient clone = client.clone();
    //增加拦截器
    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;
}
项目:materialup    文件:Api.java   
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Log.e("Log",
            String.format("Sending request %s on %s%n%s", request.url(), chain.connection(),
                    request.headers()).toString());

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.e("Log",
            String.format("Received response for %s in %.1fms%n%s", response.request().url(),
                    (t2 - t1) / 1e6d, response.headers()).toString());
    return response;
}
项目:PictureInPicturePlayground    文件:AndroidTvBoilerplateService.java   
public static AndroidTvBoilerplateService newVineyardService() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            // Catch unauthorised error
            return response;
        }
    });

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(AndroidTvBoilerplateService.ENDPOINT)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    return retrofit.create(AndroidTvBoilerplateService.class);
}
项目:apna-library    文件:ApiClient.java   
/**
 * Initializes the adapter and returns it
 * The REST Adapter is created with Retrofit methods defined in MainApiClient
 * Injects authorization headers into request
 * Inspects status codes from response
 * @return rest adapter
 */
private MainApiClient getRestAdapter() {

    httpClient = new OkHttpClient();
    httpClient.networkInterceptors().add(new StethoInterceptor());
    httpClient.interceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            com.squareup.okhttp.Response response = chain.proceed(request);
            statusCode = response.code();
            return response;
        }
    });

    mRestAdapter = new RestAdapter.Builder()
            .setEndpoint(URL_UAT)
            .setClient(new OkClient(httpClient))
            .setRequestInterceptor(authHeader())
            .setLogLevel(RestAdapter.LogLevel.FULL)
            .build();

    return mRestAdapter.create(MainApiClient.class);
}
项目:QiNiuGenertorToken    文件:Client.java   
public Client() {
    httpClient = new OkHttpClient();
    httpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            com.squareup.okhttp.Response response = chain.proceed(request);
            IpTag tag = (IpTag) request.tag();
            String ip = chain.connection().getSocket().getRemoteSocketAddress().toString();
            tag.ip = ip;
            return response;
        }
    });
    httpClient.setConnectTimeout(Config.CONNECT_TIMEOUT, TimeUnit.SECONDS);
    httpClient.setReadTimeout(Config.RESPONSE_TIMEOUT, TimeUnit.SECONDS);
}
项目:Mobile-Office    文件:ProgressHelper.java   
public static OkHttpClient addProgressResponseListener(OkHttpClient client, final IDownloadCallBack listener) {
    // 克隆
    OkHttpClient clone = client.clone();
    clone.networkInterceptors().add(new Interceptor() {

        @Override
        public Response intercept(Chain arg0) throws IOException {
            // 拦截
            Response originalResponse = arg0.proceed(arg0.request());
            return originalResponse
                    .newBuilder()
                    .body(new ProgressResponseBody(originalResponse.body(),listener))
                    .build();
        }

    });
    return clone;
}
项目:DOkHttp    文件:ProgressHelper.java   
/**
 * 包装OkHttpClient,用于下载文件的回调
 * @param client 待包装的OkHttpClient
 * @param progressListener 进度回调接口
 * @return 包装后的OkHttpClient,使用clone方法返回
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressResponseListener progressListener){
    //克隆
    OkHttpClient clone = client.clone();
    //增加拦截器
    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;
}
项目:Pas    文件:ProgressHelper.java   
/**
 * 包装OkHttpClient,用于下载文件的回调
 * @param client 待包装的OkHttpClient
 * @param progressListener 进度回调接口
 * @return 包装后的OkHttpClient,使用clone方法返回
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client,final ProgressResponseListener progressListener){
    //克隆
    OkHttpClient clone = client.clone();
    //增加拦截器
    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;
}
项目:Pas    文件:ProgressHelper.java   
/**
 * 包装OkHttpClient,用于下载文件的回调
 * @param client 待包装的OkHttpClient
 * @param progressListener 进度回调接口
 * @return 包装后的OkHttpClient,使用clone方法返回
 */
public static OkHttpClient addProgressResponseListener(OkHttpClient client, final ProgressResponseListener progressListener){
    //克隆
    OkHttpClient clone = client.clone();
    //增加拦截器
    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;
}
项目:SeriesReminder    文件:MovieApiDataSource.java   
public MovieApiDataSource() {

        // Define the interceptor, add authentication headers
        Interceptor interceptor = new Interceptor() {
            @Override
            public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                Request newRequest = chain.request().newBuilder().addHeader("User-Agent", "Retrofit-Sample-App").build();
                return chain.proceed(newRequest);
            }
        };

        // Add the interceptor to OkHttpClient
        OkHttpClient client = new OkHttpClient();
        client.interceptors().add(interceptor);

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(MOVIE_API_ENDPOINT)
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        apiService = retrofit.create(MovieApiEndpointInterface.class);
    }
项目:Vineyard    文件:VineyardService.java   
public static VineyardService newVineyardService() {
    OkHttpClient client = new OkHttpClient();
    client.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            // Catch unauthorised error
            return response;
        }
    });

    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(VineyardService.ENDPOINT)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .build();
    return retrofit.create(VineyardService.class);
}
项目:android-retrofit-test-examples    文件:LoggingInterceptor.java   
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    Log.d("Retrofit",String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    Log.d("Retrofit", String.format("Received response for %s in %.1fms%n%s",
             response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
}
项目:BlendleSDK    文件:LoggingInterceptor.java   
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();

    long t1 = System.nanoTime();
    System.out.println(String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers()));

    Response response = chain.proceed(request);

    long t2 = System.nanoTime();
    System.out.println(String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers()));

    return response;
}
项目:hacker-news-android    文件:LoginViewModel.java   
public LoginViewModel() {

        List<Interceptor> interceptors = new ArrayList<>();
        interceptors.add(new StethoInterceptor());
        interceptors.add(chain -> {
            Response response = chain.proceed(chain.request());
            List<String> cookieHeaders = response.headers("set-cookie");
            for (String header : cookieHeaders) {
                if (header.contains("user")) {
                    mUserCookie = header.split(";")[0];
                }
                else if(header.contains("__cfduid")){
                    mCfduid = header.split(";")[0];
                }
            }
            return response;
        });
        DaggerNetworkServiceComponent.builder()
                                     .okClientModule(new OkClientModule(interceptors))
                                     .appModule(HackerNewsApplication.getAppModule())
                                     .appComponent(HackerNewsApplication.getAppComponent())
                                     .build()
                                     .inject(this);
    }
项目:PhotoDiscovery    文件:App.java   
private void initPicasso() {
  File cacheDirectory = new File(getCacheDir().getAbsolutePath(), "OKHttpCache");

  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setCache(new Cache(cacheDirectory, Integer.MAX_VALUE));

  /** Dangerous interceptor that rewrites the server's cache-control header. */
  okHttpClient.networkInterceptors().add(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Response originalResponse = chain.proceed(chain.request());
      return originalResponse.newBuilder()
          .header("Cache-Control", "public, max-age=432000")
          .header("Pragma", "")
          .build();
    }
  });

  OkHttpDownloader okHttpDownloader = new OkHttpDownloader(okHttpClient);

  Picasso.Builder builder = new Picasso.Builder(this);
  builder.downloader(okHttpDownloader);

  Picasso picasso = builder.build();
  //picasso.setIndicatorsEnabled(true);
  //picasso.setLoggingEnabled(true);
  Picasso.setSingletonInstance(picasso);
}
项目:Auth0.Android    文件:OkHttpClientFactoryTest.java   
private static void verifyLoggingEnabled(OkHttpClient client, List list) {
    verify(client).interceptors();

    ArgumentCaptor<Interceptor> interceptorCaptor = ArgumentCaptor.forClass(Interceptor.class);
    verify(list).add(interceptorCaptor.capture());

    assertThat(interceptorCaptor.getValue(), is(notNullValue()));
    assertThat(interceptorCaptor.getValue(), is(instanceOf(HttpLoggingInterceptor.class)));
    assertThat(((HttpLoggingInterceptor) interceptorCaptor.getValue()).getLevel(), is(HttpLoggingInterceptor.Level.BODY));
}
项目:FMTech    文件:HttpEngine.java   
public final Response proceed(Request paramRequest)
  throws IOException
{
  this.calls = (1 + this.calls);
  if (this.index > 0)
  {
    Interceptor localInterceptor2 = (Interceptor)HttpEngine.this.client.networkInterceptors.get(-1 + this.index);
    Address localAddress = HttpEngine.this.connection.route.address;
    if ((!paramRequest.url().getHost().equals(localAddress.uriHost)) || (Util.getEffectivePort(paramRequest.url()) != localAddress.uriPort)) {
      throw new IllegalStateException("network interceptor " + localInterceptor2 + " must retain the same host and port");
    }
    if (this.calls > 1) {
      throw new IllegalStateException("network interceptor " + localInterceptor2 + " must call proceed() exactly once");
    }
  }
  Response localResponse;
  if (this.index < HttpEngine.this.client.networkInterceptors.size())
  {
    NetworkInterceptorChain localNetworkInterceptorChain = new NetworkInterceptorChain(HttpEngine.this, 1 + this.index, paramRequest);
    Interceptor localInterceptor1 = (Interceptor)HttpEngine.this.client.networkInterceptors.get(this.index);
    localResponse = localInterceptor1.intercept(localNetworkInterceptorChain);
    if (localNetworkInterceptorChain.calls != 1) {
      throw new IllegalStateException("network interceptor " + localInterceptor1 + " must call proceed() exactly once");
    }
  }
  else
  {
    HttpEngine.this.transport.writeRequestHeaders(paramRequest);
    if ((HttpEngine.this.permitsRequestBody()) && (paramRequest.body != null))
    {
      BufferedSink localBufferedSink = Okio.buffer(HttpEngine.this.transport.createRequestBody(paramRequest, paramRequest.body.contentLength()));
      paramRequest.body.writeTo(localBufferedSink);
      localBufferedSink.close();
    }
    localResponse = HttpEngine.this.readNetworkResponse();
  }
  return localResponse;
}
项目:Meducated-Ninja    文件:NetworkModule.java   
@Provides
@Singleton
OkHttpClient provideOkHttpClient(ZippyApplication application) {
    OkHttpClient client = new OkHttpClient();
    client.setConnectTimeout(60, TimeUnit.SECONDS);
    client.setReadTimeout(60, TimeUnit.SECONDS);
    client.setWriteTimeout(60, TimeUnit.SECONDS);
    File cacheFile = new File(application.getCacheDir(), "http");
    Cache cache = new Cache(cacheFile, CACHE_SIZE);
    client.setCache(cache);

    //client.networkInterceptors().add(new StethoInterceptor());
    client.networkInterceptors().add(new TimberInterceptor());

    client.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            if (response.isSuccessful() && !chain.request().headers("OkHttp-Force-Offline").isEmpty()) {
                Response.Builder responseBuilder = response.newBuilder();
                if (response.header("Cache-Control","no-cache").contains("no-cache")) {
                    responseBuilder.header("Cache-Control", "public, max-age=120");
                }
                if (response.header("Expires").equals("-1")) {
                    responseBuilder.removeHeader("Expires");
                }
                responseBuilder.removeHeader("Pragma");
                return responseBuilder.build();
            }
            return response;
        }
    });


    return client;
}
项目:transparenteapp.gt    文件:LoggingInterceptor.java   
@Override
public com.squareup.okhttp.Response intercept(Interceptor.Chain chain) throws IOException {
    Log.i("LoggingInterceptor", "inside intercept callback");
    Request request = chain.request();
    long t1 = System.nanoTime();
    String requestLog = String.format("Sending request %s on %s%n%s",
            request.url(), chain.connection(), request.headers());
    if(request.method().compareToIgnoreCase("post")==0){
        requestLog ="\n"+requestLog+"\n"+bodyToString(request);
    }
    Log.d("TAG","request"+"\n"+requestLog);
    com.squareup.okhttp.Response response = chain.proceed(request);
    long t2 = System.nanoTime();

    String responseLog = String.format("Received response for %s in %.1fms%n%s",
            response.request().url(), (t2 - t1) / 1e6d, response.headers());

    String bodyString = response.body().string();

    Log.d("TAG","response only"+"\n"+bodyString);

    Log.d("TAG","response"+"\n"+responseLog+"\n"+bodyString);

    return response.newBuilder()
            .body(ResponseBody.create(response.body().contentType(), bodyString))
            .build();

}
项目:MovieMe    文件:ApiModule.java   
@Provides
@Singleton
OkHttpClient provideOkHttpClient(Interceptor interceptor) {
    OkHttpClient okHttpClient = new OkHttpClient();

    okHttpClient.interceptors().add(interceptor);

    if (BuildConfig.DEBUG)
        okHttpClient.networkInterceptors().add(new StethoInterceptor());

    return okHttpClient;
}
项目:WeGit    文件:RetrofitUtil.java   
public static Retrofit getStringRetrofitInstance(final Context context){
    if (stringInstance == null) {
        synchronized (Retrofit.class) {
            if (stringInstance == null) {
                OkHttpClient client = new OkHttpClient();
                client.networkInterceptors().add(new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {

                        L.i(TAG,"------getStringRetrofitInstance intercept start-------");
                        Request request = chain.request();
                        GitHubAccount gitHubAccount = GitHubAccount.getInstance(context);
                        token = gitHubAccount.getAuthToken();
                        //此处build之后要返回request覆盖
                        request = request.newBuilder()
                                .addHeader("Authorization", "Token " + token)
                                .addHeader("User-Agent", "Leaking/1.0")
                                        //.addHeader("Accept", "application/vnd.github.beta+json")
                                .addHeader("Accept", "application/vnd.github.v3.raw")
                                .build();
                        // L.i(TAG, "Interceptor header = " + request.headers());
                        L.i(TAG, "Interceptor token = " + token);
                        L.i(TAG, "Interceptor request = " + request.toString());
                        L.i(TAG,"------getStringRetrofitInstance intercept end-------");
                        return chain.proceed(request);
                    }
                });

                stringInstance = new Retrofit.Builder()
                        .baseUrl(Constants.BASE_URL)
                        .addConverterFactory(new ToStringConverter())
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .client(client)
                        .build();
            }
        }
    }
    return stringInstance;
}
项目:gojira    文件:DataModule.java   
@Provides
@Singleton
Picasso providePicasso(Application app, OkHttpClient client) {
    // Create client for picasso with global client specs
    OkHttpClient picassoClient = client.clone();

    // Intercept image loading requests to add auth header
    picassoClient.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            String url = chain.request().urlString();

            // Get the current server from secure storage
            String server = Hawk.get(Preferences.KEY_SERVER);

            // Add the basic auth header only in Jira server requests
            if (url.contains(server)) {
                Request.Builder builder = chain.request().newBuilder();
                Header header = BasicAuth.getBasicAuthHeader();
                if (header != null) {
                    builder.addHeader(header.getName(), header.getValue());
                }
                return chain.proceed(builder.build());
            }

            // Skip image requests that are not for the current Jira server
            else {
                return chain.proceed(chain.request());
            }
        }
    });

    return new Picasso.Builder(app)
            .downloader(new OkHttpDownloader(picassoClient))
            .loggingEnabled(BuildConfig.DEBUG)
            .build();
}
项目:Knight    文件:AppModule.java   
@Provides
@AppScope
OkClient providesHttpClient(Application context) {
    // Setup Caching
    OkHttpClient okHttpClient = new OkHttpClient();
    try {

        File cacheDirectory = new File(context.getCacheDir(), "responses");
        Cache cache = new Cache(cacheDirectory, CACHE_SIZE);
        okHttpClient.setCache(cache);

        // Intercept and change cache headers
        okHttpClient.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .removeHeader("Expires")
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=60")
                        .build();
            }
        });

    } catch (Exception e) {
        Log.e("OKHttp", "Could not create http cache", e);
    }

    return new OkClient(okHttpClient);
}
项目:DangoReader    文件:MangaEden.java   
private static MangaEdenService buildService(Context context, final String cacheControl) {
    OkHttpClient okHttpClient = new OkHttpClient();
    // TODO try wiping cache to see what happens
    File httpCacheDirectory = new File(context.getCacheDir(), "responses");
    Cache cache = new Cache(httpCacheDirectory, 20 * 1024 * 1024);
    okHttpClient.setCache(cache);
    okHttpClient.interceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Response response = chain.proceed(chain.request());
            response.newBuilder().addHeader("Cache-Control", cacheControl);
            return response;
        }
    });

    Gson gson = new GsonBuilder()
            .registerTypeAdapter(MangaEdenMangaChapterItem.class, new MangaEdenMangaChapterItem.ChapterDeserializer())
            .registerTypeAdapter(MangaEdenImageItem.class, new MangaEdenImageItem.ImageDeserializer())
            .create();

    return new Retrofit.Builder()
            .baseUrl("https://www.mangaeden.com/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build()
            .create(MangaEdenService.class);
}
项目:gankmaku    文件:RestApi.java   
public static RestApi create(Interceptor requestInterceptor) {
  OkHttpClient client = new OkHttpClient();
  client.setConnectTimeout(30, TimeUnit.SECONDS);
  client.setReadTimeout(30, TimeUnit.SECONDS);
  client.interceptors().add(requestInterceptor);
  Retrofit retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
      .client(client)
      .addConverterFactory(MoshiConverterFactory.create())
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
      .build();
  return retrofit.create(RestApi.class);
}
项目:OkVolley    文件:OkVolley.java   
/**
 * add OkHttp interceptor
 * @param interceptor {@link Interceptor}
 */
public void addInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().addInterceptor(interceptor);
}
项目:OkVolley    文件:OkVolley.java   
/**
 * add OkHttp networkInterceptor
 * @param interceptor {@link Interceptor}
 */
public void addNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().addNetworkInterceptor(interceptor);
}
项目:OkVolley    文件:OkVolley.java   
/**
 * remove OkHttp interceptor
 * @param interceptor {@link Interceptor}
 */
public void removeInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().removeInterceptor(interceptor);
}
项目:OkVolley    文件:OkVolley.java   
/**
 * remove OkHttp networkInterceptor
 * @param interceptor {@link Interceptor}
 */
public void removeNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().removeNetworkInterceptor(interceptor);
}
项目:Android-Gradle-Samples    文件:RetrofitFragment.java   
private GithubApi createGithubApi() {
    OkHttpClient client = new OkHttpClient();


    Retrofit.Builder builder = new Retrofit.Builder().baseUrl("https://api.github.com/")
            .addConverterFactory(GsonConverterFactory.create())
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create());

    final String githubToken = getResources().getString(R.string.github_oauth_token);

    /**
     * @see https://github.com/square/okhttp/wiki/Interceptors
     */

    if (!TextUtils.isEmpty(githubToken)) {
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                Request newRequest = request.newBuilder().addHeader("Authorization", String.format("token %s", githubToken)).build();
                return chain.proceed(newRequest);
            }
        });

        builder.client(client);
    }

    return builder.build().create(GithubApi.class);
}
项目:Orpheus    文件:LastFMModule.java   
@Provides @Singleton @Named("LastFM")
    public OkHttpClient provideOkHttpClient(
            OkHttpClient okHttpClient,
            final @Named("LFMApiKey") String apiKey,
            final @Named("LFMEndpoint") String endpoint
    ) {
        OkHttpClient client = okHttpClient.clone();
        client.interceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                //recover the original request
                final Request ogReq = chain.request();
                final Request newReq;
                if (ogReq.urlString().startsWith(endpoint)) {
                    //inject our global query parameter
                    HttpUrl newUrl = ogReq.httpUrl().newBuilder()
                            .addQueryParameter("api_key", apiKey)
                            .addQueryParameter("lang", Locale.getDefault().getLanguage())
//                            .addQueryParameter("autocorrect", "1")
                            .build();
                    //update request with new url
                    newReq = ogReq.newBuilder()
                            .url(newUrl)
                            .build();
                    Timber.v("Calling %s", newReq.urlString());
                    //proceed using our updated request
                } else {
                    newReq = ogReq;
                }
                return chain.proceed(newReq);
            }
        });
        return client;
    }
项目:soundmap    文件:InstrumentationModule.java   
@Provides
@Singleton
@ApiModule.NetworkInterceptors
List<Interceptor> provideNetworkInterceptors() {
    ArrayList<Interceptor> networkInterceptors = new ArrayList<>();
    networkInterceptors.add(new StethoInterceptor());
    return networkInterceptors;
}
项目:soundmap    文件:ApiModule.java   
private static OkHttpClient createOkHttpClient(List<Interceptor> appInterceptors,
                                               List<Interceptor> networkInterceptors) {
    OkHttpClient client = new OkHttpClient();

    // Install interceptors
    client.interceptors().addAll(appInterceptors);
    client.networkInterceptors().addAll(networkInterceptors);

    return client;
}
项目:boohee_v5.6    文件:HttpEngine$NetworkInterceptorChain.java   
public Response proceed(Request request) throws IOException {
    this.calls++;
    if (this.index > 0) {
        Interceptor caller = (Interceptor) this.this$0.client.networkInterceptors().get(this
                .index - 1);
        Address address = connection().getRoute().getAddress();
        if (!request.httpUrl().host().equals(address.getUriHost()) || request.httpUrl().port
                () != address.getUriPort()) {
            throw new IllegalStateException("network interceptor " + caller + " must retain " +
                    "the same host and port");
        } else if (this.calls > 1) {
            throw new IllegalStateException("network interceptor " + caller + " must call " +
                    "proceed() exactly once");
        }
    }
    if (this.index < this.this$0.client.networkInterceptors().size()) {
        HttpEngine$NetworkInterceptorChain chain = new HttpEngine$NetworkInterceptorChain
                (this.this$0, this.index + 1, request);
        Interceptor interceptor = (Interceptor) this.this$0.client.networkInterceptors().get
                (this.index);
        Response intercept = interceptor.intercept(chain);
        if (chain.calls != 1) {
            throw new IllegalStateException("network interceptor " + interceptor + " must " +
                    "call proceed() exactly once");
        } else if (intercept != null) {
            return intercept;
        } else {
            throw new NullPointerException("network interceptor " + interceptor + " returned " +
                    "null");
        }
    }
    HttpEngine.access$000(this.this$0).writeRequestHeaders(request);
    HttpEngine.access$102(this.this$0, request);
    if (this.this$0.permitsRequestBody(request) && request.body() != null) {
        BufferedSink bufferedRequestBody = Okio.buffer(HttpEngine.access$000(this.this$0)
                .createRequestBody(request, request.body().contentLength()));
        request.body().writeTo(bufferedRequestBody);
        bufferedRequestBody.close();
    }
    Response response = HttpEngine.access$200(this.this$0);
    int code = response.code();
    if ((code != 204 && code != 205) || response.body().contentLength() <= 0) {
        return response;
    }
    throw new ProtocolException("HTTP " + code + " had non-zero Content-Length: " + response.body().contentLength());
}
项目:BaseWrapper    文件:RestClient.java   
/**
 * override to add Interceptors
 */
protected List<Interceptor> getInterceptors() {
  return new ArrayList<>();
}
项目:Auth0.Android    文件:OkHttpClientFactory.java   
private void enableLogging(OkHttpClient client) {
    Interceptor interceptor = new HttpLoggingInterceptor()
            .setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
}
项目:Auth0.Android    文件:OkHttpClientFactoryTest.java   
private static void verifyLoggingDisabled(OkHttpClient client, List list) {
    verify(client, never()).interceptors();
    verify(list, never()).add(any(Interceptor.class));
}
项目:FMTech    文件:CurlLoggingInterceptor.java   
public final Response intercept(Interceptor.Chain paramChain)
  throws IOException
{
  Request localRequest = paramChain.request();
  String str1 = VolleyLog.TAG;
  StringBuilder localStringBuilder = new StringBuilder();
  localStringBuilder.append("curl ");
  localStringBuilder.append("-X ");
  localStringBuilder.append(localRequest.method);
  localStringBuilder.append(" ");
  Iterator localIterator = localRequest.headers.names().iterator();
  while (localIterator.hasNext())
  {
    String str4 = (String)localIterator.next();
    localStringBuilder.append("--header \"");
    localStringBuilder.append(str4);
    localStringBuilder.append(": ");
    List localList = localRequest.headers.values(str4);
    int i = localList.size();
    for (int j = 0; j < i; j++)
    {
      localStringBuilder.append((String)localList.get(j));
      if (j < i - 1) {
        localStringBuilder.append(", ");
      }
    }
    localStringBuilder.append("\" ");
  }
  URI localURI = localRequest.uri();
  localStringBuilder.append("\"");
  localStringBuilder.append(localURI);
  localStringBuilder.append("\"");
  ByteArrayOutputStream localByteArrayOutputStream;
  if (localRequest.body != null)
  {
    RequestBody localRequestBody = localRequest.body;
    if (localRequestBody != null)
    {
      if (localRequestBody.contentLength() >= 1024L) {
        break label417;
      }
      localByteArrayOutputStream = new ByteArrayOutputStream();
      Buffer localBuffer = new Buffer();
      localRequestBody.writeTo(localBuffer);
      localBuffer.writeTo(localByteArrayOutputStream, localBuffer.size);
      localBuffer.copyTo(localByteArrayOutputStream, 0L, localBuffer.size);
      if (!isBinaryContent(localRequest.headers, localRequestBody.contentType())) {
        break label389;
      }
      String str3 = Base64.encodeToString(localByteArrayOutputStream.toByteArray(), 2);
      localStringBuilder.insert(0, "echo '" + str3 + "' | base64 -d > /tmp/$$.bin; ");
      localStringBuilder.append(" --data-binary @/tmp/$$.bin");
    }
  }
  for (;;)
  {
    Log.v(str1, localStringBuilder.toString());
    return paramChain.proceed(localRequest);
    label389:
    String str2 = localByteArrayOutputStream.toString();
    localStringBuilder.append(" --data-ascii \"").append(str2).append("\"");
    continue;
    label417:
    localStringBuilder.append(" [TOO MUCH DATA TO INCLUDE]");
  }
}
项目:dhis2-android-dashboard    文件:RepoManager.java   
private static Interceptor provideInterceptor(Credentials credentials) {
    return new AuthInterceptor(credentials.getUsername(), credentials.getPassword());
}