List of usage examples for com.squareup.okhttp OkHttpClient interceptors
List interceptors
To view the source code for com.squareup.okhttp OkHttpClient interceptors.
Click Source Link
From source file:com.seu.mycircle.model.repository.toolbox.HttpManager.java
License:Apache License
public static Retrofit.Builder getBuilder(OkHttpClient client) { if (builder == null) { client.setReadTimeout(10, TimeUnit.MINUTES); client.setConnectTimeout(10, TimeUnit.MINUTES); client.setWriteTimeout(10, TimeUnit.MINUTES); //print//from w ww .java 2 s . co m client.interceptors().add(new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() { @Override public void log(String message) { if (message.startsWith("{")) { Logger.json(message); } else { Logger.i("ApiManger", message); } } })); //add custom headers client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request().newBuilder().addHeader("platform", "android") .addHeader("appVersion", BuildConfig.VERSION_NAME).build(); return chain.proceed(request); } }); builder = new Retrofit.Builder().client(client).addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()); } return builder; }
From source file:com.tanmay.blip.fragments.RandomFragment.java
License:Apache License
@Nullable @Override// ww w . j ava 2s. c o m public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_random, container, false); setHasOptionsMenu(true); swipeRefreshLayout = (SwipeRefreshLayout) rootView.findViewById(R.id.swipeRefresh); title = (TextView) rootView.findViewById(R.id.title); date = (TextView) rootView.findViewById(R.id.date); alt = (TextView) rootView.findViewById(R.id.alt); img = (ImageView) rootView.findViewById(R.id.img); favourite = (ImageView) rootView.findViewById(R.id.favourite); browser = rootView.findViewById(R.id.open_in_browser); transcript = rootView.findViewById(R.id.transcript); imgContainer = rootView.findViewById(R.id.img_container); share = rootView.findViewById(R.id.share); explain = rootView.findViewById(R.id.help); browser.setOnClickListener(this); transcript.setOnClickListener(this); imgContainer.setOnClickListener(this); favourite.setOnClickListener(this); share.setOnClickListener(this); explain.setOnClickListener(this); databaseManager = new DatabaseManager(getActivity()); simpleDateFormat = new SimpleDateFormat("MMMM dd, yyyy (EEEE)", Locale.getDefault()); OkHttpClient picassoClient = BlipApplication.getInstance().client.clone(); picassoClient.interceptors().add(BlipUtils.REWRITE_CACHE_CONTROL_INTERCEPTOR); new Picasso.Builder(getActivity()).downloader(new OkHttpDownloader(picassoClient)).build(); int num = 0; if (savedInstanceState != null) num = savedInstanceState.getInt("NUM"); loadComic(num); swipeRefreshLayout.setColorSchemeResources(R.color.accent); swipeRefreshLayout.setOnRefreshListener(this); return rootView; }
From source file:com.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java
License:Open Source License
/** * Builds a RestAdapter./*www . j a v a 2s.c om*/ */ private static RestAdapter buildRestAdapter(final Session session, String endpointHost, final OAuth2Helper oAuth2Helper, RestAdapter.LogLevel logLevel, OkHttpClient httpClient) throws IOException { RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { Credential credential = session.getCredential(); if (credential != null) { oAuth2Helper.refreshCredentialIfNeeded(credential); requestFacade.addHeader("Authorization", "Bearer " + credential.getAccessToken()); } else { requestFacade.addHeader("Authorization", "Token " + session.getServerToken()); } if (session.getLocale() != null) { requestFacade.addHeader("Accept-Language", session.getLocale().getLanguage()); } requestFacade.addHeader("X-Uber-User-Agent", "Java Rides SDK v" + LIB_VERSION); } }; if (httpClient == null) { httpClient = new OkHttpClient(); httpClient.setConnectTimeout(1, TimeUnit.MINUTES); httpClient.setReadTimeout(1, TimeUnit.MINUTES); httpClient.setFollowRedirects(false); httpClient.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request oldRequest = chain.request(); Response response = chain.proceed(oldRequest); if (response.isRedirect()) { String redirectUrl = response.header(HttpHeaders.LOCATION); Request newRequest = oldRequest.newBuilder().url(redirectUrl).build(); return chain.proceed(newRequest); } return response; } }); } return new RestAdapter.Builder().setEndpoint(endpointHost) .setConverter(new GsonConverter(new GsonBuilder().create())) .setRequestInterceptor(requestInterceptor).setClient(new OkClient(httpClient)).setLogLevel(logLevel) .build(); }
From source file:com.vavian.mockretrofitrequests.rest.service.RestClient.java
License:Apache License
public static IRestService getClient() { if (mRestService == null) { final OkHttpClient client = new OkHttpClient(); client.interceptors().add(new FakeInterceptor()); final Retrofit retrofit = new Retrofit.Builder() // Using custom Jackson Converter to parse JSON // Add dependencies: // com.squareup.retrofit:converter-jackson:2.0.0-beta2 .addConverterFactory(JacksonConverterFactory.create()) // Endpoint .baseUrl(IRestService.ENDPOINT).client(client).build(); mRestService = retrofit.create(IRestService.class); }/*from ww w. j av a 2 s . c om*/ return mRestService; }
From source file:es.ffgiraldez.comicsearch.data.api.RestDataSource.java
License:Apache License
public RestDataSource() { OkHttpClient client = new OkHttpClient(); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); client.interceptors().add(httpLoggingInterceptor); endpoint = new Retrofit.Builder().baseUrl(ComicVineApi.BASE_URL).client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build().create(ComicVineApi.class); }
From source file:io.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {/*from w w w .j av a 2 s. 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 {/*w w w . j a v a 2s.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.fabric8.openshift.client.internal.OpenShiftOAuthInterceptor.java
License:Apache License
private String authorize() { try {/*from ww w . j a v a 2 s. co m*/ OkHttpClient clone = client.clone(); clone.interceptors().remove(this); String credential = Credentials.basic(config.getUsername(), new String(config.getPassword())); URL url = new URL(URLUtils.join(config.getMasterUrl(), AUTHORIZE_PATH)); Response response = clone .newCall(new Request.Builder().get().url(url).header(AUTHORIZATION, credential).build()) .execute(); response.body().close(); String token = response.priorResponse().networkResponse().header(LOCATION); token = token.substring(token.indexOf(BEFORE_TOKEN) + BEFORE_TOKEN.length()); token = token.substring(0, token.indexOf(AFTER_TOKEN)); return token; } catch (Exception e) { throw KubernetesClientException.launderThrowable(e); } }
From source file:io.macgyver.core.okhttp.LoggingInterceptorTest.java
License:Apache License
@Test public void testIt() throws IOException { x.enqueue(/*from w w w . j av a2 s .c om*/ new MockResponse().setBody("{\"hello\":\"world\"}").addHeader("Content-type", "application/json")); OkHttpClient c = new OkHttpClient(); c.interceptors() .add(LoggingInterceptor.create(LoggerFactory.getLogger(LoggingInterceptorTest.class), Level.NONE)); c.newCall(new Request.Builder().url(x.url("/foo")).addHeader("Authorization", "foo").build()).execute(); }
From source file:io.macgyver.core.okhttp.LoggingInterceptorTest.java
License:Apache License
@Test public void testResponseException() throws IOException { x.enqueue(//from w w w . j a va 2 s.c o m new MockResponse().setBody("{\"hello\":\"world\"}").addHeader("Content-type", "application/json")); OkHttpClient c = new OkHttpClient(); c.interceptors().add(new BlowingLoggingInterceptor(LoggerFactory.getLogger(BlowingLoggingInterceptor.class), Level.BODY)); c.newCall(new Request.Builder().url(x.url("/foo")).addHeader("Authorization", "foo").build()).execute(); }