List of usage examples for com.squareup.okhttp Interceptor Interceptor
Interceptor
From source file:com.anony.okhttp.sample.LoggingInterceptors.java
License:Apache License
public LoggingInterceptors() { client.networkInterceptors().add(new Interceptor() { @Override//from w w w . ja v a 2 s . c o m public Response intercept(Chain chain) throws IOException { long t1 = System.nanoTime(); Request request = chain.request(); logger.info(String.format("Sending request %s on %s%n%s", request.httpUrl(), chain.connection(), request.headers())); Response response = chain.proceed(request); long t2 = System.nanoTime(); logger.info(String.format("Received response for %s in %.1fms%n%s", request.httpUrl(), (t2 - t1) / 1e6d, response.headers())); return response; } }); }
From source file:com.anony.okhttp.sample.Progress.java
License:Apache License
public void run() throws Exception { Request request = new Request.Builder().url("https://publicobject.com/helloworld.txt").build(); final ProgressListener progressListener = new ProgressListener() { @Override//from ww w. j a v a 2s. com public void update(long bytesRead, long contentLength, boolean done) { System.out.println(bytesRead); System.out.println(contentLength); System.out.println(done); System.out.format("%d%% done\n", (100 * bytesRead) / contentLength); } }; client.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(); } }); Response response = client.newCall(request).execute(); if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); System.out.println(response.body().string()); }
From source file:com.belatrixsf.allstars.utils.di.modules.RetrofitModule.java
License:Open Source License
@Singleton @Provides/* ww w. j av a 2s .co m*/ public Retrofit provideRetrofit() { HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient(); client.interceptors().add(loggingInterceptor); client.interceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { String token = PreferencesManager.get().getToken(); if (token != null) { Request request = chain.request().newBuilder().addHeader("Authorization", "Token " + token) .build(); return chain.proceed(request); } return chain.proceed(chain.request()); } }); return new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()) .baseUrl(BuildConfig.BASE_URL).client(client).build(); }
From source file:com.brq.wallet.external.glidera.api.GlideraService.java
private GlideraService(@NonNull final NetworkParameters networkParameters) { Preconditions.checkNotNull(networkParameters); this.networkParameters = networkParameters; this.baseUrl = getBaseUrl(networkParameters); if (networkParameters.isTestnet()) { clientId = TESTNET_CLIENT_ID;/* w w w. jav a 2 s . c om*/ } else { clientId = MAINNET_CLIENT_ID; } /** * The Sha256 HMAC hash of the message. Use the secret matching the access_key to hash the message. * The message is the concatenation of the X-ACCESS-NONCE + URI of the request + message body JSON. * The final X-ACCESS-SIGNATURE is the HmacSha256 of the UTF-8 encoding of the message as a Hex encoded string */ final Interceptor apiCredentialInterceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); if (_oAuth1Response != null) { Request.Builder requestBuilder = request.newBuilder(); synchronized (_nonce) { final String nonce = _nonce.getNonceString(); final String uri = request.urlString(); String message = nonce + uri; if (request.body() != null && request.body().contentLength() > 0) { Buffer bodyBuffer = new Buffer(); request.body().writeTo(bodyBuffer); byte[] bodyBytes = bodyBuffer.readByteArray(); String body = new String(bodyBytes, Charsets.UTF_8); message += body; } final byte[] messageBytes = message.getBytes(Charsets.UTF_8); final byte[] secretBytes = _oAuth1Response.getSecret().getBytes(Charsets.UTF_8); final byte[] signatureBytes = Hmac.hmacSha256(secretBytes, messageBytes); ByteArrayOutputStream stream = new ByteArrayOutputStream(); Hex.encode(signatureBytes, stream); final String signature = stream.toString(); request = requestBuilder.header(HEADER_ACCESS_KEY, _oAuth1Response.getAccess_key()) .header(HEADER_ACCESS_NONCE, nonce).header(HEADER_ACCESS_SIGNATURE, signature) .build(); } } return chain.proceed(request); } }; OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(15000, TimeUnit.MILLISECONDS); client.setReadTimeout(15000, TimeUnit.MILLISECONDS); client.networkInterceptors().add(apiCredentialInterceptor); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.); objectMapper.registerModule(new WapiJsonModule()); /* We should always add client_id to the header */ RequestInterceptor requestInterceptor = new RequestInterceptor() { @Override public void intercept(RequestFacade requestFacade) { requestFacade.addHeader(HEADER_CLIENT_ID, clientId); } }; /* Create the json adapter */ RestAdapter adapter = new RestAdapter.Builder().setEndpoint(baseUrl + "/api/" + API_VERSION + "/") //.setLogLevel(RestAdapter.LogLevel.FULL) .setLogLevel(RestAdapter.LogLevel.BASIC).setLog(new AndroidLog("Glidera")) .setConverter(new JacksonConverter(objectMapper)).setClient(new NullBodyAwareOkClient(client)) .setRequestInterceptor(requestInterceptor).build(); glideraApi = adapter.create(GlideraApi.class); }
From source file:com.dreamdigitizers.androidsoundcloudapi.core.Api.java
private Api(final String pClientId, final String pOauthToken) { OkHttpClient okHttpClient = new OkHttpClient(); okHttpClient.interceptors().add(new Interceptor() { @Override//from w ww . ja v a 2 s . c om public Response intercept(Chain pChain) throws IOException { Request request = pChain.request(); HttpUrl.Builder builder = request.httpUrl().newBuilder(); builder.addQueryParameter("client_id", pClientId); if (!TextUtils.isEmpty(pOauthToken)) { builder.addQueryParameter("oauth_token", pOauthToken); } HttpUrl httpUrl = builder.build(); Log.d(Api.TAG, httpUrl.url().toString()); request = request.newBuilder().url(httpUrl).build(); Response response = pChain.proceed(request); String bodyString = response.body().string(); response = response.newBuilder() .body(ResponseBody.create(response.body().contentType(), bodyString)).build(); Log.d(Api.TAG, bodyString); return response; } }); Retrofit retrofit = new Retrofit.Builder().baseUrl(IApi.API_URL__BASE).client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build(); this.mApi = retrofit.create(IApi.class); }
From source file:com.facebook.buck.artifact_cache.ArtifactCaches.java
License:Apache License
private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig, BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) { URI uri = buckConfig.getHttpCacheUrl(); int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds(); boolean doStore = buckConfig.getHttpCacheReadMode(); final String host = buckConfig.getHostToReportToRemoteCacheServer(); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new Interceptor() { @Override//from w w w .j ava 2s.com public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", host).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache("http", fetchClient, client, uri, doStore, projectFilesystem, buckEventBus); }
From source file:com.facebook.buck.cli.ArtifactCaches.java
License:Apache License
private static ArtifactCache createHttpArtifactCache(ArtifactCacheBuckConfig buckConfig, BuckEventBus buckEventBus, ProjectFilesystem projectFilesystem) { URL url = buckConfig.getHttpCacheUrl(); int timeoutSeconds = buckConfig.getHttpCacheTimeoutSeconds(); boolean doStore = buckConfig.getHttpCacheReadMode(); final String host = buckConfig.getHostToReportToRemoteCacheServer(); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); client.networkInterceptors().add(new Interceptor() { @Override//from ww w.ja va 2 s. com public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", host).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache("http", fetchClient, client, url, doStore, projectFilesystem, buckEventBus, Hashing.crc32()); }
From source file:com.facebook.buck.cli.BuckConfig.java
License:Apache License
private ArtifactCache createHttpArtifactCache() { URL url;/*from w ww . ja v a 2 s .co m*/ try { url = new URL(getValue("cache", "http_url").or(DEFAULT_HTTP_URL)); } catch (MalformedURLException e) { throw new HumanReadableException(e, "Malformed [cache]http_url: %s", e.getMessage()); } int timeoutSeconds = Integer .parseInt(getValue("cache", "http_timeout_seconds").or(DEFAULT_HTTP_CACHE_TIMEOUT_SECONDS)); boolean doStore = readCacheMode("http_mode", DEFAULT_HTTP_CACHE_MODE); // Setup the defaut client to use. OkHttpClient client = new OkHttpClient(); final String localhost = getLocalhost(); client.networkInterceptors().add(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { return chain.proceed(chain.request().newBuilder() .addHeader("X-BuckCache-User", System.getProperty("user.name", "<unknown>")) .addHeader("X-BuckCache-Host", localhost).build()); } }); client.setConnectTimeout(timeoutSeconds, TimeUnit.SECONDS); client.setConnectionPool(new ConnectionPool( // It's important that this number is greater than the `-j` parallelism, // as if it's too small, we'll overflow the reusable connection pool and // start spamming new connections. While this isn't the best location, // the other current option is setting this wherever we construct a `Build` // object and have access to the `-j` argument. However, since that is // created in several places leave it here for now. /* maxIdleConnections */ 200, /* keepAliveDurationMs */ TimeUnit.MINUTES.toMillis(5))); // For fetches, use a client with a read timeout. OkHttpClient fetchClient = client.clone(); fetchClient.setReadTimeout(timeoutSeconds, TimeUnit.SECONDS); return new HttpArtifactCache(fetchClient, client, url, doStore, projectFilesystem, Hashing.crc32()); }
From source file:com.gdkm.sfk.utils.coreProgress.ProgressHelper.java
License:Apache License
/** * OkHttpClient// www . j a va 2 s . c o m * @param client OkHttpClient * @param progressListener ? * @return ?OkHttpClientclone */ 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; }
From source file:com.hexdo.hexexamples.network.GOERetrofit.java
License:Open Source License
public static <S> S createService(Class<S> serviceClass, final String authToken) { List<Interceptor> interceptors = httpClient.interceptors(); interceptors.clear();/* ww w. j a v a 2s . com*/ if (authToken != null) { interceptors.add(new Interceptor() { @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException { Request original = chain.request(); // Request customization: add request headers Request.Builder requestBuilder = original.newBuilder().header("Authorization", authToken) .method(original.method(), original.body()); Request request = requestBuilder.build(); return chain.proceed(request); } }); } HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); // set your desired log level logging.setLevel(HttpLoggingInterceptor.Level.BODY); interceptors.add(logging); Retrofit retrofit = builder.client(httpClient).build(); return retrofit.create(serviceClass); }