Search in sources :

Example 16 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class WebSocketHttpTest method webSocketAndNetworkInterceptors.

@Test
public void webSocketAndNetworkInterceptors() throws IOException {
    client = client.newBuilder().addNetworkInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            // Network interceptors don't execute.
            throw new AssertionError();
        }
    }).build();
    webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
    WebSocket webSocket = newWebSocket();
    clientListener.assertOpen();
    webSocket.close(1000, null);
    WebSocket server = serverListener.assertOpen();
    server.close(1000, null);
}
Also used : Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) WebSocket(okhttp3.WebSocket) Test(org.junit.Test)

Example 17 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class OkHttpURLConnection method connect.

@Override
public void connect() throws IOException {
    if (executed)
        return;
    Call call = buildCall();
    executed = true;
    call.enqueue(this);
    synchronized (lock) {
        try {
            while (connectPending && response == null && callFailure == null) {
                // Wait 'til the network interceptor is reached or the call fails.
                lock.wait();
            }
            if (callFailure != null) {
                throw propagate(callFailure);
            }
        } catch (InterruptedException e) {
            throw new InterruptedIOException();
        }
    }
}
Also used : Call(okhttp3.Call) InterruptedIOException(java.io.InterruptedIOException)

Example 18 with Interceptor

use of okhttp3.Interceptor in project okhttp by square.

the class WebSocketHttpTest method webSocketAndApplicationInterceptors.

@Test
public void webSocketAndApplicationInterceptors() throws IOException {
    final AtomicInteger interceptedCount = new AtomicInteger();
    client = client.newBuilder().addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Chain chain) throws IOException {
            assertNull(chain.request().body());
            Response response = chain.proceed(chain.request());
            assertEquals("Upgrade", response.header("Connection"));
            assertTrue("", response.body().source().exhausted());
            interceptedCount.incrementAndGet();
            return response;
        }
    }).build();
    webServer.enqueue(new MockResponse().withWebSocketUpgrade(serverListener));
    WebSocket webSocket = newWebSocket();
    clientListener.assertOpen();
    assertEquals(1, interceptedCount.get());
    webSocket.close(1000, null);
    WebSocket server = serverListener.assertOpen();
    server.close(1000, null);
}
Also used : Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) MockResponse(okhttp3.mockwebserver.MockResponse) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor) WebSocket(okhttp3.WebSocket) Test(org.junit.Test)

Example 19 with Interceptor

use of okhttp3.Interceptor in project Fast-Android-Networking by amitshekhariitbhu.

the class InternalNetworking method performDownloadRequest.

public static Response performDownloadRequest(final ANRequest request) throws ANError {
    Request okHttpRequest;
    Response okHttpResponse;
    try {
        Request.Builder builder = new Request.Builder().url(request.getUrl());
        addHeadersToRequestBuilder(builder, request);
        builder = builder.get();
        if (request.getCacheControl() != null) {
            builder.cacheControl(request.getCacheControl());
        }
        okHttpRequest = builder.build();
        OkHttpClient okHttpClient;
        if (request.getOkHttpClient() != null) {
            okHttpClient = request.getOkHttpClient().newBuilder().cache(sHttpClient.cache()).addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        } else {
            okHttpClient = sHttpClient.newBuilder().addNetworkInterceptor(new Interceptor() {

                @Override
                public Response intercept(Chain chain) throws IOException {
                    Response originalResponse = chain.proceed(chain.request());
                    return originalResponse.newBuilder().body(new ResponseProgressBody(originalResponse.body(), request.getDownloadProgressListener())).build();
                }
            }).build();
        }
        request.setCall(okHttpClient.newCall(okHttpRequest));
        final long startTime = System.currentTimeMillis();
        final long startBytes = TrafficStats.getTotalRxBytes();
        okHttpResponse = request.getCall().execute();
        Utils.saveFile(okHttpResponse, request.getDirPath(), request.getFileName());
        final long timeTaken = System.currentTimeMillis() - startTime;
        if (okHttpResponse.cacheResponse() == null) {
            final long finalBytes = TrafficStats.getTotalRxBytes();
            final long diffBytes;
            if (startBytes == TrafficStats.UNSUPPORTED || finalBytes == TrafficStats.UNSUPPORTED) {
                diffBytes = okHttpResponse.body().contentLength();
            } else {
                diffBytes = finalBytes - startBytes;
            }
            ConnectionClassManager.getInstance().updateBandwidth(diffBytes, timeTaken);
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, okHttpResponse.body().contentLength(), false);
        } else if (request.getAnalyticsListener() != null) {
            Utils.sendAnalytics(request.getAnalyticsListener(), timeTaken, -1, 0, true);
        }
    } catch (IOException ioe) {
        try {
            File destinationFile = new File(request.getDirPath() + File.separator + request.getFileName());
            if (destinationFile.exists()) {
                destinationFile.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        throw new ANError(ioe);
    }
    return okHttpResponse;
}
Also used : OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ANRequest(com.androidnetworking.common.ANRequest) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) IOException(java.io.IOException) Response(okhttp3.Response) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(com.androidnetworking.interceptors.HttpLoggingInterceptor) File(java.io.File)

Example 20 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)

Aggregations

IOException (java.io.IOException)37 Interceptor (okhttp3.Interceptor)36 Request (okhttp3.Request)29 MockResponse (okhttp3.mockwebserver.MockResponse)29 Response (okhttp3.Response)25 Test (org.junit.Test)25 OkHttpClient (okhttp3.OkHttpClient)24 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)24 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)9 File (java.io.File)8 Retrofit (retrofit2.Retrofit)8 Provides (dagger.Provides)6 Singleton (javax.inject.Singleton)6 Cache (okhttp3.Cache)5 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)3 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