List of usage examples for com.squareup.okhttp OkHttpClient networkInterceptors
List networkInterceptors
To view the source code for com.squareup.okhttp OkHttpClient networkInterceptors.
Click Source Link
From source file:com.rowland.movies.ApplicationController.java
License:Apache License
public static Retrofit getRetrofit() { // Set custom date format for Gson Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); SessionRequestInterceptor sessionRequestInterceptor = new SessionRequestInterceptor(); // set your desired log level logging.setLevel(HttpLoggingInterceptor.Level.BODY); // Our client OkHttpClient client = new OkHttpClient(); // Set other interceptors client.networkInterceptors().add(new StethoInterceptor()); // Set SessionRequestInterceptor instance as interceptor client.interceptors().add(sessionRequestInterceptor); // Set HttpLoggingInterceptor instance as last interceptor client.interceptors().add(logging);/*from w w w . j a va2s .co m*/ //To send out network requests to an API_MOVIE_URL, we need to use the Retrofit builder class Retrofit retrofit = new Retrofit.Builder().baseUrl(EBaseURlTypes.MOVIE_API_BASE_URL.getUrlType()) .addConverterFactory(GsonConverterFactory.create(gson)).client(client).build(); // Wollah! Retrofit instance is served hot. return retrofit; }
From source file:com.rowland.moviesquire.ApplicationController.java
License:Apache License
public static Retrofit getRetrofit() { // Set custom date format for Gson Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) .excludeFieldsWithoutExposeAnnotation().setDateFormat("yyyy-MM-dd").create(); HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); SessionRequestInterceptor sessionRequestInterceptor = new SessionRequestInterceptor(); // set your desired log level logging.setLevel(HttpLoggingInterceptor.Level.BODY); // Our client OkHttpClient client = new OkHttpClient(); // Set other interceptors client.networkInterceptors().add(new StethoInterceptor()); // Set SessionRequestInterceptor instance as interceptor client.interceptors().add(sessionRequestInterceptor); // Set HttpLoggingInterceptor instance as last interceptor client.interceptors().add(logging);/* w ww. ja v a 2 s . c om*/ //To send out network requests to an API_MOVIE_URL, we need to use the Retrofit builder class Retrofit retrofit = new Retrofit.Builder().baseUrl(EBaseURlTypes.MOVIE_API_BASE_URL.getUrlType()) .addConverterFactory(GsonConverterFactory.create(gson)).client(client).build(); // Wollah! Retrofit instance is served hot. return retrofit; }
From source file:com.sam_chordas.android.stockhawk.app.retofit.RestClientPublic.java
License:Apache License
private OkHttpClient getClient() { OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); client.interceptors().add(interceptor); client.networkInterceptors().add(new Interceptor() { @Override//from ww w . j a v a 2 s. co m public Response intercept(Chain chain) throws IOException { Request request = chain.request(); HttpUrl url = request.httpUrl().newBuilder() .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_format), App.getGlobalContext().getString(R.string.url_query_json)) .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_diagnostics), App.getGlobalContext().getString(R.string.url_query_diagnostics_value)) .addQueryParameter(App.getGlobalContext().getString(R.string.url_query_evn), App.getGlobalContext().getString(R.string.url_query_evn_value)) .build(); request = request.newBuilder().url(url).build(); return chain.proceed(request); } }); return client; }
From source file:com.veaer.gank.request.LineRetrofit.java
License:Open Source License
LineRetrofit() { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(12, TimeUnit.SECONDS); int cacheSize = 10 * 1024 * 1024; // 10 MiB cache = new Cache(FileUtils.getHttpCacheDir(), cacheSize); client.setCache(cache);/*from ww w. j ava 2 s . c o m*/ client.networkInterceptors().add(new CacheInterceptor()); RestAdapter restAdapter = new RestAdapter.Builder().setClient(new OkClient(client)) .setEndpoint("http://gank.avosapps.com/api/").setConverter(new GsonConverter(gson)).build(); service = restAdapter.create(Line.class); }
From source file:io.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {//w ww . jav a 2s .c o m OkHttpClient httpClient = new OkHttpClient(); httpClient.setConnectionPool(ConnectionPool.getDefault()); // Follow any redirects httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); if (config.isTrustCerts()) { httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } if (usesUnixSocket(config)) { URL masterURL = new URL(config.getDockerUrl().replaceFirst(UNIX_SCHEME, FILE_SCHEME)); httpClient.setSocketFactory(new UnixSocketFactory(masterURL.getFile())); config.setDockerUrl(UNIX_FAKE_URL); } TrustManager[] trustManagers = SSLUtils.trustManagers(config); KeyManager[] keyManagers = SSLUtils.keyManagers(config); if (keyManagers != null || trustManagers != null || config.isTrustCerts()) { try { SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } } if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) { httpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.getScheme())) continue; String credential = Credentials.basic(config.getUsername(), config.getPassword()); return request.newBuilder().header("Authorization", credential).build(); } return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } else if (config.getOauthToken() != null) { httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request authReq = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + config.getOauthToken()).build(); return chain.proceed(authReq); } }); } Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); if (reqLogger.isTraceEnabled()) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.networkInterceptors().add(loggingInterceptor); } if (config.getConnectionTimeout() > 0) { httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); } if (config.getRequestTimeout() > 0) { httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); } // Only check proxy if it's a full URL with protocol if (config.getDockerUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getDockerUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { try { URL proxyUrl = getProxyUrl(config); if (proxyUrl != null) { httpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()))); } } catch (MalformedURLException e) { throw new DockerClientException("Invalid proxy server configuration", e); } } return httpClient; } catch (Exception e) { throw DockerClientException.launderThrowable(e); } }
From source file:io.fabric8.kubernetes.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {/* www .j av a2s .c o m*/ OkHttpClient httpClient = new OkHttpClient(); // Follow any redirects httpClient.setFollowRedirects(true); httpClient.setFollowSslRedirects(true); if (config.isTrustCerts()) { httpClient.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); } TrustManager[] trustManagers = SSLUtils.trustManagers(config); KeyManager[] keyManagers = SSLUtils.keyManagers(config); if (keyManagers != null || trustManagers != null || config.isTrustCerts()) { try { SSLContext sslContext = SSLUtils.sslContext(keyManagers, trustManagers, config.isTrustCerts()); httpClient.setSslSocketFactory(sslContext.getSocketFactory()); } catch (GeneralSecurityException e) { throw new AssertionError(); // The system has no TLS. Just give up. } } if (isNotNullOrEmpty(config.getUsername()) && isNotNullOrEmpty(config.getPassword())) { httpClient.setAuthenticator(new Authenticator() { @Override public Request authenticate(Proxy proxy, Response response) throws IOException { List<Challenge> challenges = response.challenges(); Request request = response.request(); HttpUrl url = request.httpUrl(); for (int i = 0, size = challenges.size(); i < size; i++) { Challenge challenge = challenges.get(i); if (!"Basic".equalsIgnoreCase(challenge.getScheme())) continue; String credential = Credentials.basic(config.getUsername(), config.getPassword()); return request.newBuilder().header("Authorization", credential).build(); } return null; } @Override public Request authenticateProxy(Proxy proxy, Response response) throws IOException { return null; } }); } else if (config.getOauthToken() != null) { httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request authReq = chain.request().newBuilder() .addHeader("Authorization", "Bearer " + config.getOauthToken()).build(); return chain.proceed(authReq); } }); } Logger reqLogger = LoggerFactory.getLogger(HttpLoggingInterceptor.class); if (reqLogger.isTraceEnabled()) { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); httpClient.networkInterceptors().add(loggingInterceptor); } if (config.getConnectionTimeout() > 0) { httpClient.setConnectTimeout(config.getConnectionTimeout(), TimeUnit.MILLISECONDS); } if (config.getRequestTimeout() > 0) { httpClient.setReadTimeout(config.getRequestTimeout(), TimeUnit.MILLISECONDS); } // Only check proxy if it's a full URL with protocol if (config.getMasterUrl().toLowerCase().startsWith(Config.HTTP_PROTOCOL_PREFIX) || config.getMasterUrl().startsWith(Config.HTTPS_PROTOCOL_PREFIX)) { try { URL proxyUrl = getProxyUrl(config); if (proxyUrl != null) { httpClient.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUrl.getHost(), proxyUrl.getPort()))); } } catch (MalformedURLException e) { throw new KubernetesClientException("Invalid proxy server configuration", e); } } if (config.getUserAgent() != null && !config.getUserAgent().isEmpty()) { httpClient.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request agent = chain.request().newBuilder().header("User-Agent", config.getUserAgent()) .build(); return chain.proceed(agent); } }); } return httpClient; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
From source file:io.reark.rxgithubapp.shared.utils.StethoInstrumentation.java
License:Open Source License
@VisibleForTesting void addInterceptor(@NonNull final OkHttpClient httpClient, @NonNull final Interceptor interceptor) { checkNotNull(httpClient);/*from ww w .j a va 2 s . c om*/ checkNotNull(interceptor); httpClient.networkInterceptors().add(interceptor); }
From source file:io.reark.rxgithubapp.shared.utils.StethoInstrumentationTest.java
License:Open Source License
@Test public void testDecorateNetwork() { @SuppressWarnings("unchecked") List<Interceptor> interceptors = mock(List.class); OkHttpClient okHttpClient = mock(OkHttpClient.class); when(okHttpClient.networkInterceptors()).thenReturn(interceptors); instrumentation.decorateNetwork(okHttpClient); verify(instrumentation).addInterceptor(eq(okHttpClient), eq(interceptor)); }
From source file:io.reark.rxgithubapp.utils.StethoInstrumentation.java
License:Open Source License
@VisibleForTesting void addInterceptor(@NonNull OkHttpClient httpClient, @NonNull Interceptor interceptor) { Preconditions.checkNotNull(httpClient, "Http Client cannot be null."); Preconditions.checkNotNull(interceptor, "Interceptor cannot be null."); httpClient.networkInterceptors().add(interceptor); }
From source file:keywhiz.cli.ClientUtils.java
License:Apache License
/** * Creates a {@link OkHttpClient} to start a TLS connection. * * @param devTrustStore if not null, uses the provided TrustStore instead of whatever is * configured in the JVM. This is a convenient way to allow developers to * start playing with Keywhiz right away. This option should not be used in * production systems. * @param cookies list of cookies to include in the client. * @return new http client./*from ww w. ja v a 2s . c o m*/ */ public static OkHttpClient sslOkHttpClient(@Nullable KeyStore devTrustStore, List<HttpCookie> cookies) { checkNotNull(cookies); SSLContext sslContext; try { TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(devTrustStore); TrustManager[] trustManagers = trustManagerFactory.getTrustManagers(); sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(new KeyManager[0], trustManagers, new SecureRandom()); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw Throwables.propagate(e); } SSLSocketFactory socketFactory = sslContext.getSocketFactory(); OkHttpClient client = new OkHttpClient().setSslSocketFactory(socketFactory) .setConnectionSpecs(Arrays.asList(ConnectionSpec.MODERN_TLS)).setFollowSslRedirects(false); client.setRetryOnConnectionFailure(false); client.networkInterceptors().add(new XsrfTokenInterceptor("XSRF-TOKEN", "X-XSRF-TOKEN")); CookieManager cookieManager = new CookieManager(); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); cookies.forEach(c -> cookieManager.getCookieStore().add(null, c)); client.setCookieHandler(cookieManager); return client; }