com.squareup.okhttp.Interceptor Java Examples

The following examples show how to use com.squareup.okhttp.Interceptor. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: LoginViewModel.java    From hacker-news-android with Apache License 2.0 6 votes vote down vote up
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);
    }
 
Example #2
Source File: ProgressHelper.java    From NewsMe with Apache License 2.0 6 votes vote down vote up
/**
 * 包装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;
}
 
Example #3
Source File: Api.java    From materialup with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #4
Source File: LoggingInterceptor.java    From android-retrofit-test-examples with MIT License 6 votes vote down vote up
@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;
}
 
Example #5
Source File: ProgressHelper.java    From Pas with Apache License 2.0 6 votes vote down vote up
/**
 * 包装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;
}
 
Example #6
Source File: ProgressHelper.java    From Pas with Apache License 2.0 6 votes vote down vote up
/**
 * 包装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;
}
 
Example #7
Source File: Log.java    From tencentcloud-sdk-java with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
  Request request = chain.request();
  String req = ("send request, request url: " + request.urlString() + ". request headers information: " + request.headers().toString());
  req = req.replaceAll("\n", ";");
  this.debug(req);
  Response response = chain.proceed(request);
  String resp = ("recieve response, response url: " + response.request().urlString() + ", response headers: " + response.headers().toString() + ",response body information: " + response.body().toString());
  resp = resp.replaceAll("\n", ";");
  this.debug(resp);
  return response;
}
 
Example #8
Source File: OkHttpMetricsInterceptor.java    From kork with Apache License 2.0 5 votes vote down vote up
@Override
public Response intercept(Interceptor.Chain chain) throws IOException {
  try {
    return (Response) doIntercept(chain);
  } catch (IOException ioe) {
    throw ioe;
  } catch (Exception ex) {
    throw new IOException(ex);
  }
}
 
Example #9
Source File: OkVolley.java    From OkVolley with Apache License 2.0 5 votes vote down vote up
/**
 * remove OkHttp networkInterceptor
 * @param interceptor {@link Interceptor}
 */
public void removeNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().removeNetworkInterceptor(interceptor);
}
 
Example #10
Source File: OkVolley.java    From OkVolley with Apache License 2.0 5 votes vote down vote up
/**
 * remove OkHttp interceptor
 * @param interceptor {@link Interceptor}
 */
public void removeInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().removeInterceptor(interceptor);
}
 
Example #11
Source File: OkVolley.java    From OkVolley with Apache License 2.0 5 votes vote down vote up
/**
 * add OkHttp networkInterceptor
 * @param interceptor {@link Interceptor}
 */
public void addNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().addNetworkInterceptor(interceptor);
}
 
Example #12
Source File: OkVolley.java    From OkVolley with Apache License 2.0 5 votes vote down vote up
/**
 * add OkHttp interceptor
 * @param interceptor {@link Interceptor}
 */
public void addInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    getDefaultHttpStack().addInterceptor(interceptor);
}
 
Example #13
Source File: RetrofitUtil.java    From WeGit with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #14
Source File: App.java    From Studio with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
    super.onCreate();

    AVOSCloud.initialize(this, VALUE_AVOS_APPID, VALUE_AVOS_APPKEY);
    OkHttpClient okHttpClient = new OkHttpClient();
    //OKHttp的使用
    okHttpClient.networkInterceptors().add(new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            return chain.proceed(chain.request().newBuilder()
                    .header(KEY_BUILD_VERSION, BuildConfig.VERSION_NAME)
                    .build());
        }
    });

    if (BuildConfig.DEBUG) {
        okHttpClient.networkInterceptors().add(new LoggingInterceptor());
    }

    //初始化Gson
    Gson gson = new GsonBuilder()
            .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
            .setDateFormat(DATE_FORMAT_PATTERN)
            .create();


    //初始化Retrofit
    retrofit = new Retrofit.Builder()
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
            .baseUrl(Api.BASE_URL)
            .build();
}
 
Example #15
Source File: App.java    From PhotoDiscovery with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: OkHttp2PinningInterceptor.java    From TrustKit-Android with MIT License 5 votes vote down vote up
@Override public Response intercept(Interceptor.Chain chain) throws IOException {
    Request request = chain.request();
    String serverHostname = request.url().getHost();

    mTrustManager.setServerHostname(serverHostname);
    return chain.proceed(request);
}
 
Example #17
Source File: OkHttpClientFactoryTest.java    From Auth0.Android with MIT License 5 votes vote down vote up
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));
}
 
Example #18
Source File: OkHttpClientFactoryTest.java    From Auth0.Android with MIT License 4 votes vote down vote up
private static void verifyLoggingDisabled(OkHttpClient client, List list) {
    verify(client, never()).interceptors();
    verify(list, never()).add(any(Interceptor.class));
}
 
Example #19
Source File: RetrofitUtil.java    From WeGit with Apache License 2.0 4 votes vote down vote up
public static Retrofit getRetrofitWithoutTokenInstance(final Context context) {
    if (jsonInstance_withoutToken == null) {
        synchronized (Retrofit.class) {
            if (jsonInstance_withoutToken == null) {
                OkHttpClient client = new OkHttpClient();
                client.networkInterceptors().add(new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                        L.i(TAG,"------getRetrofitWithoutTokenInstance intercept start-------");

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


                Gson gson = null;
                GsonBuilder builder = new GsonBuilder();
                builder.registerTypeAdapter(Event.class, new EventFormatter());
                gson = builder.create();
                jsonInstance_withoutToken = new Retrofit.Builder()
                        .baseUrl(Constants.BASE_URL)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build();

            }
        }
    }
    return jsonInstance_withoutToken;
}
 
Example #20
Source File: OkHttpClientFactory.java    From Auth0.Android with MIT License 4 votes vote down vote up
private void enableLogging(OkHttpClient client) {
    Interceptor interceptor = new HttpLoggingInterceptor()
            .setLevel(HttpLoggingInterceptor.Level.BODY);
    client.interceptors().add(interceptor);
}
 
Example #21
Source File: OkHttp2Helper.java    From TrustKit-Android with MIT License 4 votes vote down vote up
/**
 * Returns an {@link com.squareup.okhttp.Interceptor} used to parse the hostname of the
 * {@link Request} URL and then save the hostname in the {@link OkHttpRootTrustManager} which will
 * later be used for Certificate Pinning.
 */
@NonNull
@RequiresApi(api = 17)
public static Interceptor getPinningInterceptor() {
    return new OkHttp2PinningInterceptor((OkHttpRootTrustManager)trustManager);
}
 
Example #22
Source File: RetrofitUtil.java    From WeGit with Apache License 2.0 4 votes vote down vote up
public static Retrofit getJsonRetrofitInstance(final Context context) {
    if (jsonInstance == null) {
        synchronized (Retrofit.class) {
            if (jsonInstance == null) {
                OkHttpClient client = new OkHttpClient();
                client.networkInterceptors().add(new Interceptor() {
                    @Override
                    public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
                        L.i(TAG,"------getJsonRetrofitInstance intercept start-------");
                        Request request = chain.request();
                        GitHubAccount gitHubAccount = GitHubAccount.getInstance(context);
                        token = gitHubAccount.getAuthToken();
                        request = request.newBuilder()
                                .removeHeader("User-Agent")
                                .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 token = " + token);
                        L.i(TAG, "Interceptor request = " + request.toString());
                        L.i(TAG,"------getJsonRetrofitInstance intercept end-------");
                        return chain.proceed(request);
                    }
                });

                Gson gson = null;
                GsonBuilder builder = new GsonBuilder();
                builder.registerTypeAdapter(Event.class, new EventFormatter());
                gson = builder.create();
                jsonInstance = new Retrofit.Builder()
                        .baseUrl(Constants.BASE_URL)
                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .addConverterFactory(GsonConverterFactory.create(gson))
                        .client(client)
                        .build();

            }
        }
    }
    return jsonInstance;
}
 
Example #23
Source File: OkHttpStack.java    From OkVolley with Apache License 2.0 4 votes vote down vote up
public void addInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    this.mClient.interceptors().add(interceptor);
}
 
Example #24
Source File: OkHttpStack.java    From OkVolley with Apache License 2.0 4 votes vote down vote up
public void addNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    this.mClient.networkInterceptors().add(interceptor);
}
 
Example #25
Source File: OkHttpStack.java    From OkVolley with Apache License 2.0 4 votes vote down vote up
public void removeInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    this.mClient.interceptors().remove(interceptor);
}
 
Example #26
Source File: OkHttpStack.java    From OkVolley with Apache License 2.0 4 votes vote down vote up
public void removeNetworkInterceptor(Interceptor interceptor) {
    if (interceptor == null) {
        return;
    }
    this.mClient.networkInterceptors().remove(interceptor);
}
 
Example #27
Source File: OkClientModule.java    From hacker-news-android with Apache License 2.0 4 votes vote down vote up
public OkClientModule(List<Interceptor> interceptorList) {
    mInterceptorList = interceptorList;
}
 
Example #28
Source File: RepoManager.java    From dhis2-android-dashboard with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private static Interceptor provideInterceptor(Credentials credentials) {
    return new AuthInterceptor(credentials.getUsername(), credentials.getPassword());
}
 
Example #29
Source File: MetricsInterceptor.java    From kork with Apache License 2.0 4 votes vote down vote up
protected final Object doIntercept(Object chainObject) throws IOException {
  long start = System.nanoTime();
  boolean wasSuccessful = false;
  int statusCode = -1;

  Interceptor.Chain chain =
      (chainObject instanceof Interceptor.Chain) ? (Interceptor.Chain) chainObject : null;
  okhttp3.Interceptor.Chain chain3 =
      (chainObject instanceof okhttp3.Interceptor.Chain)
          ? (okhttp3.Interceptor.Chain) chainObject
          : null;

  Request request = (chain != null) ? chain.request() : null;
  okhttp3.Request request3 = (chain3 != null) ? chain3.request() : null;

  List<String> missingHeaders = new ArrayList<>();
  String method = null;
  URL url = null;

  try {
    String xSpinAnonymous = MDC.get(Header.XSpinnakerAnonymous);

    if (xSpinAnonymous == null && !skipHeaderCheck) {
      for (Header header : Header.values()) {
        String headerValue =
            (request != null)
                ? request.header(header.getHeader())
                : request3.header(header.getHeader());

        if (header.isRequired() && StringUtils.isEmpty(headerValue)) {
          missingHeaders.add(header.getHeader());
        }
      }
    }

    Object response;

    if (chain != null) {
      method = request.method();
      url = request.url();
      response = chain.proceed(request);
      statusCode = ((Response) response).code();
    } else {
      method = request3.method();
      url = request3.url().url();
      response = chain3.proceed(request3);
      statusCode = ((okhttp3.Response) response).code();
    }

    wasSuccessful = true;
    return response;
  } finally {
    boolean missingAuthHeaders = missingHeaders.size() > 0;

    if (missingAuthHeaders) {
      List<String> stack =
          Arrays.stream(Thread.currentThread().getStackTrace())
              .map(StackTraceElement::toString)
              .filter(x -> x.contains("com.netflix.spinnaker"))
              .collect(Collectors.toList());

      String stackTrace = String.join("\n\tat ", stack);
      log.warn(
          String.format(
              "Request %s:%s is missing %s authentication headers and will be treated as anonymous.\nRequest from: %s",
              method, url, missingHeaders, stackTrace));
    }

    recordTimer(
        registry.get(),
        url,
        System.nanoTime() - start,
        statusCode,
        wasSuccessful,
        !missingAuthHeaders);
  }
}
 
Example #30
Source File: HttpConnection.java    From tencentcloud-sdk-java with Apache License 2.0 4 votes vote down vote up
public void addInterceptors(Interceptor interceptor) {
  this.client.interceptors().add(interceptor);
}