Search in sources :

Example 1 with Interceptor

use of okhttp3.Interceptor in project GeekNews by codeestX.

the class HttpModule method provideClient.

@Singleton
@Provides
OkHttpClient provideClient(OkHttpClient.Builder builder) {
    if (BuildConfig.DEBUG) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
        builder.addInterceptor(loggingInterceptor);
    }
    File cacheFile = new File(Constants.PATH_CACHE);
    Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
    Interceptor cacheInterceptor = new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!SystemUtil.isNetworkConnected()) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
            }
            Response response = chain.proceed(request);
            if (SystemUtil.isNetworkConnected()) {
                int maxAge = 0;
                // 有网络时, 不缓存, 最大保存时长为0
                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader("Pragma").build();
            } else {
                // 无网络时,设置超时为4周
                int maxStale = 60 * 60 * 24 * 28;
                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
            }
            return response;
        }
    };
    //        Interceptor apikey = new Interceptor() {
    //            @Override
    //            public Response intercept(Chain chain) throws IOException {
    //                Request request = chain.request();
    //                request = request.newBuilder()
    //                        .addHeader("apikey",Constants.KEY_API)
    //                        .build();
    //                return chain.proceed(request);
    //            }
    //        }
    //        设置统一的请求头部参数
    //        builder.addInterceptor(apikey);
    //设置缓存
    builder.addNetworkInterceptor(cacheInterceptor);
    builder.addInterceptor(cacheInterceptor);
    builder.cache(cache);
    //设置超时
    builder.connectTimeout(10, TimeUnit.SECONDS);
    builder.readTimeout(20, TimeUnit.SECONDS);
    builder.writeTimeout(20, TimeUnit.SECONDS);
    //错误重连
    builder.retryOnConnectionFailure(true);
    return builder.build();
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 2 with Interceptor

use of okhttp3.Interceptor in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClientTest method testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse.

@Test
public void testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse() throws Exception {
    // Make mock response
    Buffer buffer = new Buffer();
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write("content".getBytes());
    gzipOut.close();
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + 201 + " " + "OK").setBody(buffer).setHeader("Content-Encoding", "gzip");
    // Start mock server
    server.enqueue(mockResponse);
    server.start();
    ParseHttpClient client = new ParseOkHttpClient(10000, null);
    final Semaphore done = new Semaphore(0);
    // Add plain interceptor to disable decompress response stream
    client.addExternalInterceptor(new ParseNetworkInterceptor() {

        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();
            ParseHttpResponse parseResponse = chain.proceed(chain.getRequest());
            // Make sure the response we get from the interceptor is the raw gzip stream
            byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
            assertArrayEquals(byteOut.toByteArray(), content);
            // We need to set a new stream since we have read it
            return new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(byteOut.toByteArray())).build();
        }
    });
    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.url("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl).setMethod(ParseHttpRequest.Method.GET).build();
    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);
    // Make sure the response we get is ungziped by OkHttp library
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals("content".getBytes(), content);
    // Make sure interceptor is called
    assertTrue(done.tryAcquire(10, TimeUnit.SECONDS));
    server.shutdown();
}
Also used : Buffer(okio.Buffer) MockResponse(okhttp3.mockwebserver.MockResponse) ParseHttpRequest(com.parse.http.ParseHttpRequest) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Semaphore(java.util.concurrent.Semaphore) IOException(java.io.IOException) GZIPOutputStream(java.util.zip.GZIPOutputStream) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ByteArrayInputStream(java.io.ByteArrayInputStream) ParseHttpResponse(com.parse.http.ParseHttpResponse) Test(org.junit.Test)

Example 3 with Interceptor

use of okhttp3.Interceptor in project BigImageViewer by Piasy.

the class GlideProgressSupport method createInterceptor.

private static Interceptor createInterceptor(final ResponseProgressListener listener) {
    return new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Response response = chain.proceed(request);
            return response.newBuilder().body(new OkHttpProgressResponseBody(request.url(), response.body(), listener)).build();
        }
    };
}
Also used : Response(okhttp3.Response) Request(okhttp3.Request) Interceptor(okhttp3.Interceptor)

Example 4 with Interceptor

use of okhttp3.Interceptor in project android-oss by kickstarter.

the class ApplicationModule method provideHttpLoggingInterceptor.

@Provides
@Singleton
@NonNull
HttpLoggingInterceptor provideHttpLoggingInterceptor() {
    final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
    return interceptor;
}
Also used : HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) NonNull(android.support.annotation.NonNull) Provides(dagger.Provides)

Example 5 with Interceptor

use of okhttp3.Interceptor in project zipkin by openzipkin.

the class TraceZipkinElasticsearchHttpStorageAutoConfiguration method elasticsearchOkHttpClientBuilder.

@Bean
@Qualifier("zipkinElasticsearchHttp")
@ConditionalOnMissingBean
OkHttpClient.Builder elasticsearchOkHttpClientBuilder() {
    // have to indirect to unwind a circular dependency
    Interceptor tracingInterceptor = new Interceptor() {

        Interceptor delegate = BraveTracingInterceptor.builder(brave).serverName("elasticsearch").build();

        @Override
        public Response intercept(Chain chain) throws IOException {
            // Only join traces, don't start them. This prevents LocalCollector's thread from amplifying.
            if (brave.serverSpanThreadBinder().getCurrentServerSpan() != null && brave.serverSpanThreadBinder().getCurrentServerSpan().getSpan() != null) {
                return delegate.intercept(chain);
            }
            return chain.proceed(chain.request());
        }
    };
    BraveExecutorService tracePropagatingExecutor = BraveExecutorService.wrap(new Dispatcher().executorService(), brave);
    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    builder.addInterceptor(tracingInterceptor);
    builder.addNetworkInterceptor(tracingInterceptor);
    builder.dispatcher(new Dispatcher(tracePropagatingExecutor));
    return builder;
}
Also used : BraveExecutorService(com.github.kristofa.brave.BraveExecutorService) OkHttpClient(okhttp3.OkHttpClient) Dispatcher(okhttp3.Dispatcher) Interceptor(okhttp3.Interceptor) BraveTracingInterceptor(com.github.kristofa.brave.okhttp.BraveTracingInterceptor) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Qualifier(org.springframework.beans.factory.annotation.Qualifier) ConditionalOnBean(org.springframework.boot.autoconfigure.condition.ConditionalOnBean) ConditionalOnMissingBean(org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean) Bean(org.springframework.context.annotation.Bean)

Aggregations

IOException (java.io.IOException)35 Interceptor (okhttp3.Interceptor)33 MockResponse (okhttp3.mockwebserver.MockResponse)29 Request (okhttp3.Request)26 Test (org.junit.Test)25 Response (okhttp3.Response)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 OkHttpClient (okhttp3.OkHttpClient)20 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)10 File (java.io.File)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)4 Retrofit (retrofit2.Retrofit)4 InterruptedIOException (java.io.InterruptedIOException)3 Call (okhttp3.Call)3 HttpUrl (okhttp3.HttpUrl)3 NonNull (android.support.annotation.NonNull)2 ANResponse (com.androidnetworking.common.ANResponse)2 ResponseProgressBody (com.androidnetworking.internal.ResponseProgressBody)2