Search in sources :

Example 86 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project okhttp by square.

the class HttpOverHttp2Test method connectionShutdownAfterHealthCheck.

/**
   * This simulates a race condition where we receive a healthy HTTP/2 connection and just prior to
   * writing our request, we get a GOAWAY frame from the server.
   */
@Test
public void connectionShutdownAfterHealthCheck() throws Exception {
    server.enqueue(new MockResponse().setSocketPolicy(SocketPolicy.DISCONNECT_AT_END).setBody("ABC"));
    server.enqueue(new MockResponse().setBody("DEF"));
    OkHttpClient client2 = client.newBuilder().addNetworkInterceptor(new Interceptor() {

        boolean executedCall;

        @Override
        public Response intercept(Chain chain) throws IOException {
            if (!executedCall) {
                // At this point, we have a healthy HTTP/2 connection. This call will trigger the
                // server to send a GOAWAY frame, leaving the connection in a shutdown state.
                executedCall = true;
                Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
                Response response = call.execute();
                assertEquals("ABC", response.body().string());
                // Wait until the GOAWAY has been processed.
                RealConnection connection = (RealConnection) chain.connection();
                while (connection.isHealthy(false)) ;
            }
            return chain.proceed(chain.request());
        }
    }).build();
    Call call = client2.newCall(new Request.Builder().url(server.url("/")).build());
    Response response = call.execute();
    assertEquals("DEF", response.body().string());
    assertEquals(0, server.takeRequest().getSequenceNumber());
    assertEquals(0, server.takeRequest().getSequenceNumber());
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) Response(okhttp3.Response) MockResponse(okhttp3.mockwebserver.MockResponse) Call(okhttp3.Call) RealConnection(okhttp3.internal.connection.RealConnection) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) RecordedRequest(okhttp3.mockwebserver.RecordedRequest) Interceptor(okhttp3.Interceptor) Test(org.junit.Test)

Example 87 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project okhttp by square.

the class RealInterceptorChain method proceed.

public Response proceed(Request request, StreamAllocation streamAllocation, HttpCodec httpCodec, RealConnection connection) throws IOException {
    if (index >= interceptors.size())
        throw new AssertionError();
    calls++;
    // If we already have a stream, confirm that the incoming request will use it.
    if (this.httpCodec != null && !this.connection.supportsUrl(request.url())) {
        throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must retain the same host and port");
    }
    // If we already have a stream, confirm that this is the only call to chain.proceed().
    if (this.httpCodec != null && calls > 1) {
        throw new IllegalStateException("network interceptor " + interceptors.get(index - 1) + " must call proceed() exactly once");
    }
    // Call the next interceptor in the chain.
    RealInterceptorChain next = new RealInterceptorChain(interceptors, streamAllocation, httpCodec, connection, index + 1, request);
    Interceptor interceptor = interceptors.get(index);
    Response response = interceptor.intercept(next);
    // Confirm that the next interceptor made its required call to chain.proceed().
    if (httpCodec != null && index + 1 < interceptors.size() && next.calls != 1) {
        throw new IllegalStateException("network interceptor " + interceptor + " must call proceed() exactly once");
    }
    // Confirm that the intercepted response isn't null.
    if (response == null) {
        throw new NullPointerException("interceptor " + interceptor + " returned null");
    }
    return response;
}
Also used : Response(okhttp3.Response) Interceptor(okhttp3.Interceptor)

Example 88 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project Parse-SDK-Android by ParsePlatform.

the class ParseOkHttpClient method addExternalInterceptor.

/**
   * For OKHttpClient, since it does not expose any interface for us to check the raw response
   * stream, we have to use OKHttp networkInterceptors. Instead of using our own interceptor list,
   * we use OKHttp inner interceptor list.
   * @param parseNetworkInterceptor
   */
@Override
/* package */
void addExternalInterceptor(final ParseNetworkInterceptor parseNetworkInterceptor) {
    OkHttpClient.Builder builder = okHttpClient.newBuilder();
    builder.networkInterceptors().add(new Interceptor() {

        @Override
        public Response intercept(final Chain okHttpChain) throws IOException {
            Request okHttpRequest = okHttpChain.request();
            // Transfer OkHttpRequest to ParseHttpRequest
            final ParseHttpRequest parseRequest = getParseHttpRequest(okHttpRequest);
            // Capture OkHttpResponse
            final Capture<Response> okHttpResponseCapture = new Capture<>();
            final ParseHttpResponse parseResponse = parseNetworkInterceptor.intercept(new ParseNetworkInterceptor.Chain() {

                @Override
                public ParseHttpRequest getRequest() {
                    return parseRequest;
                }

                @Override
                public ParseHttpResponse proceed(ParseHttpRequest parseRequest) throws IOException {
                    // Use OKHttpClient to send request
                    Request okHttpRequest = ParseOkHttpClient.this.getRequest(parseRequest);
                    Response okHttpResponse = okHttpChain.proceed(okHttpRequest);
                    okHttpResponseCapture.set(okHttpResponse);
                    return getResponse(okHttpResponse);
                }
            });
            final Response okHttpResponse = okHttpResponseCapture.get();
            // Ideally we should build newOkHttpResponse only based on parseResponse, however
            // ParseHttpResponse does not have all the info we need to build the newOkHttpResponse, so
            // we rely on the okHttpResponse to generate the builder and change the necessary info
            // inside
            Response.Builder newOkHttpResponseBuilder = okHttpResponse.newBuilder();
            // Set status
            newOkHttpResponseBuilder.code(parseResponse.getStatusCode()).message(parseResponse.getReasonPhrase());
            // Set headers
            if (parseResponse.getAllHeaders() != null) {
                for (Map.Entry<String, String> entry : parseResponse.getAllHeaders().entrySet()) {
                    newOkHttpResponseBuilder.header(entry.getKey(), entry.getValue());
                }
            }
            // Set body
            newOkHttpResponseBuilder.body(new ResponseBody() {

                @Override
                public MediaType contentType() {
                    if (parseResponse.getContentType() == null) {
                        return null;
                    }
                    return MediaType.parse(parseResponse.getContentType());
                }

                @Override
                public long contentLength() {
                    return parseResponse.getTotalSize();
                }

                @Override
                public BufferedSource source() {
                    // interceptor.
                    if (parseResponse.getContent() == null) {
                        return null;
                    }
                    return Okio.buffer(Okio.source(parseResponse.getContent()));
                }
            });
            return newOkHttpResponseBuilder.build();
        }
    });
    okHttpClient = builder.build();
}
Also used : ParseHttpRequest(com.parse.http.ParseHttpRequest) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) ParseHttpRequest(com.parse.http.ParseHttpRequest) IOException(java.io.IOException) Capture(bolts.Capture) ResponseBody(okhttp3.ResponseBody) Response(okhttp3.Response) ParseHttpResponse(com.parse.http.ParseHttpResponse) Interceptor(okhttp3.Interceptor) ParseNetworkInterceptor(com.parse.http.ParseNetworkInterceptor) ParseHttpResponse(com.parse.http.ParseHttpResponse)

Example 89 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project run-wallet-android by runplay.

the class IotaMsgCore method postConstruct.

/**
 * added header for IRI
 */
private void postConstruct() {
    final String nodeUrl = protocol + "://" + host + ":" + port;
    // Create OkHttpBuilder
    Authenticator auth = new Authenticator() {

        @Nullable
        @Override
        public Request authenticate(Route route, okhttp3.Response response) throws IOException {
            if (responseCount(response) >= 3) {
                // If we've failed 3 times, give up. - in real life, never give up!!
                return null;
            }
            String credential = Credentials.basic(uname, upassword);
            return response.request().newBuilder().header("Authorization", credential).build();
        }
    };
    final OkHttpClient client = new OkHttpClient.Builder().readTimeout(5000, TimeUnit.SECONDS).authenticator(auth).addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request newRequest;
            newRequest = request.newBuilder().addHeader(X_IOTA_API_VERSION_HEADER_NAME, X_IOTA_API_VERSION_HEADER_VALUE).build();
            return chain.proceed(newRequest);
        }
    }).connectTimeout(5000, TimeUnit.SECONDS).build();
    // use client to create Retrofit service
    final Retrofit retrofit = new Retrofit.Builder().baseUrl(nodeUrl).addConverterFactory(GsonConverterFactory.create()).client(client).build();
    service = retrofit.create(IotaAPIService.class);
    log.debug("Jota-API Java proxy pointing to node url: '{}'", nodeUrl);
}
Also used : IotaAPIService(jota.IotaAPIService) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Response(retrofit2.Response) Retrofit(retrofit2.Retrofit) Interceptor(okhttp3.Interceptor) Authenticator(okhttp3.Authenticator) Route(okhttp3.Route)

Example 90 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project Awesome-WanAndroid by JsonChao.

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 = chain -> {
        Request request = chain.request();
        if (!CommonUtils.isNetworkConnected()) {
            request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
        }
        Response response = chain.proceed(request);
        if (CommonUtils.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;
    };
    // 设置缓存
    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);
    // cookie认证
    builder.cookieJar(new CookiesManager());
    return builder.build();
}
Also used : Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) Cache(okhttp3.Cache) GeeksApis(json.chao.com.wanandroid.core.http.api.GeeksApis) CacheControl(okhttp3.CacheControl) Singleton(javax.inject.Singleton) File(java.io.File) WanAndroidUrl(json.chao.com.wanandroid.di.qualifier.WanAndroidUrl) Retrofit(retrofit2.Retrofit) RxJava2CallAdapterFactory(retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory) CommonUtils(json.chao.com.wanandroid.utils.CommonUtils) TimeUnit(java.util.concurrent.TimeUnit) Constants(json.chao.com.wanandroid.app.Constants) Module(dagger.Module) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) BuildConfig(json.chao.com.wanandroid.BuildConfig) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Response(okhttp3.Response) CookiesManager(json.chao.com.wanandroid.core.http.cookies.CookiesManager) Provides(dagger.Provides) Response(okhttp3.Response) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache) CookiesManager(json.chao.com.wanandroid.core.http.cookies.CookiesManager) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Aggregations

Interceptor (okhttp3.Interceptor)138 Request (okhttp3.Request)61 OkHttpClient (okhttp3.OkHttpClient)54 Response (okhttp3.Response)51 IOException (java.io.IOException)45 Test (org.junit.Test)29 Retrofit (retrofit2.Retrofit)27 File (java.io.File)15 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)13 Cache (okhttp3.Cache)9 HttpUrl (okhttp3.HttpUrl)8 Interceptor (com.pushtorefresh.storio3.Interceptor)7 Dispatcher (okhttp3.Dispatcher)7 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)6 X509TrustManager (javax.net.ssl.X509TrustManager)6 CachingAuthenticator (com.burgstaller.okhttp.digest.CachingAuthenticator)5 Provides (dagger.Provides)5 Singleton (javax.inject.Singleton)5 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)5 OAuth (com.arm.mbed.cloud.sdk.internal.devicedirectory.auth.OAuth)4