List of usage examples for com.squareup.okhttp Interceptor Interceptor
Interceptor
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 w ww . j a va 2 s . com 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.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/* ww w .ja v a2s . c o 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.uber.sdk.rides.client.internal.RetrofitUberRidesClient.java
License:Open Source License
/** * Builds a RestAdapter./*from w w w . j a v a2 s .c o m*/ */ 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:im.ene.lab.dowy.internal.PartDownloader.java
License:Open Source License
public PartDownloader(OkHttpClient client, Request request, OnProgressListener listener) { this.client = client; this.request = request; this.listener = listener; this.client.networkInterceptors().add(new Interceptor() { @Override//from ww w.j a va2 s . c o m public Response intercept(Chain chain) throws IOException { Response originalResponse = chain.proceed(chain.request()); return originalResponse.newBuilder() .body(new ProgressResponseBody(originalResponse.body(), PartDownloader.this.listener)) .build(); } }); }
From source file:io.fabric8.docker.client.utils.HttpClientUtils.java
License:Apache License
public static OkHttpClient createHttpClient(final Config config) { try {//from ww w. j ava2 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 ww .jav a2 s.com*/ 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:mobi.lab.sample_event_logging_library.service.LogPostService.java
License:Open Source License
@Override public void onCreate() { super.onCreate(); //TODO: starting from Android 5.0 we could use JobScheduler (currently not in support libraries) handler = new Handler(); handler.postDelayed(timedRunnable, Config.MAX_TIME_INTERVAL_BETWEEN_REQUESTS); logEventsForRequest = new ArrayList<>(); OkHttpClient client = new OkHttpClient(); client.interceptors().add(new Interceptor() { @Override//w ww . java 2 s .com public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request request = chain.request(); Log.d(TAG, String.format("\n\nrequest:%s\nheaders:%s\n" + "url:%s", request.body().toString(), request.headers(), request.httpUrl().toString())); return chain.proceed(request); } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(Network.BASE_API_URL) .addConverterFactory(GsonConverterFactory.create()).client(client).build(); logEventService = retrofit.create(LogEventRequest.class); if (checkCallingOrSelfPermission( Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkCallingOrSelfPermission( Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { //TODO: ask for permission if not given Log.d(TAG, "location permission not granted"); isLocationServicesEnabled = false; return; } isLocationServicesEnabled = true; final LocationManager locationManager = (LocationManager) getApplicationContext() .getSystemService(Context.LOCATION_SERVICE); final Criteria criteria = new Criteria(); criteria.setAccuracy(Criteria.ACCURACY_FINE); Log.d(TAG, "requesting user location"); locationManager.requestLocationUpdates(Config.LOCATION_UPDATES_MIN_TIME, Config.LOCATION_UPDATES_MIN_DISTANCE, criteria, this, null); }
From source file:net.ltgt.resteasy.client.okhttp.OkHttpClientEngineTest.java
License:Apache License
@Before public void configureClient() { okHttpClient = new OkHttpClient(); okHttpClient.interceptors().add(new Interceptor() { @Override//w ww . j av a2 s . co m public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder().tag(TAG).build()); } }); client = new ResteasyClientBuilder().httpEngine(new OkHttpClientEngine(new OkHttpClient())).build(); }
From source file:net.qiujuer.common.okhttp.core.HttpCore.java
License:Apache License
public OkHttpClient interceptToProgressResponse() { mOkHttpClient.networkInterceptors().add(new Interceptor() { @Override/*from ww w .j a va2 s .c o m*/ public Response intercept(Chain chain) throws IOException { Response response = chain.proceed(chain.request()); ResponseBody body = new ForwardResponseBody(response.body()); return response.newBuilder().body(body).build(); } }); return mOkHttpClient; }
From source file:objective.taskboard.jira.endpoint.JiraEndpoint.java
License:Open Source License
public <S> S request(Class<S> service, String username, String password) { OkHttpClient client = new OkHttpClient(); client.setReadTimeout(60, TimeUnit.SECONDS); client.setConnectTimeout(60, TimeUnit.SECONDS); client.interceptors().add(new AuthenticationInterceptor(username, password)); client.interceptors().add(new Interceptor() { @Override/* w ww. j av a 2 s . c o m*/ public Response intercept(Chain chain) throws IOException { com.squareup.okhttp.Request request = chain.request(); Response response = chain.proceed(request); int retryCount = 0; while (response.code() == HttpStatus.GATEWAY_TIMEOUT.value() && retryCount < 3) { Uninterruptibles.sleepUninterruptibly(5, TimeUnit.SECONDS); response = chain.proceed(request); retryCount++; } if (!response.isSuccessful()) log.error(request.urlString() + " request failed."); return response; } }); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.registerModule(new TaskboardJacksonModule()); objectMapper.configure(FAIL_ON_UNKNOWN_PROPERTIES, false); RestAdapter retrofit = new RestAdapter.Builder().setEndpoint(jiraProperties.getUrl()) .setConverter(new JacksonConverter(objectMapper)).setClient(new OkClient(client)).build(); return retrofit.create(service); }