Search in sources :

Example 46 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project apollo-android by apollographql.

the class ApolloPrefetchTest method setup.

@Before
public void setup() {
    cacheStore = new MockHttpCacheStore();
    cacheStore.delegate = new DiskLruHttpCacheStore(inMemoryFileSystem, new File("/cache/"), Integer.MAX_VALUE);
    okHttpClient = new OkHttpClient.Builder().addInterceptor(new Interceptor() {

        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            lastHttRequest = chain.request();
            lastHttResponse = chain.proceed(lastHttRequest);
            return lastHttResponse;
        }
    }).dispatcher(new Dispatcher(Utils.immediateExecutorService())).build();
    apolloClient = ApolloClient.builder().serverUrl(server.url("/")).okHttpClient(okHttpClient).dispatcher(Utils.immediateExecutor()).httpCache(new ApolloHttpCache(cacheStore, null)).build();
}
Also used : ApolloHttpCache(com.apollographql.apollo.cache.http.ApolloHttpCache) DiskLruHttpCacheStore(com.apollographql.apollo.cache.http.DiskLruHttpCacheStore) Dispatcher(okhttp3.Dispatcher) File(java.io.File) ApolloServerInterceptor(com.apollographql.apollo.internal.interceptor.ApolloServerInterceptor) Interceptor(okhttp3.Interceptor) Before(org.junit.Before)

Example 47 with Interceptor

use of com.pushtorefresh.storio3.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) ANRequest(com.androidnetworking.common.ANRequest) Request(okhttp3.Request) IOException(java.io.IOException) ANError(com.androidnetworking.error.ANError) IOException(java.io.IOException) Response(okhttp3.Response) HttpLoggingInterceptor(com.androidnetworking.interceptors.HttpLoggingInterceptor) Interceptor(okhttp3.Interceptor) File(java.io.File)

Example 48 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project Fast-Android-Networking by amitshekhariitbhu.

the class RxInternalNetworking method generateDownloadObservable.

public static <T> Observable<T> generateDownloadObservable(final RxANRequest request) {
    Request okHttpRequest;
    Request.Builder builder = new Request.Builder().url(request.getUrl());
    InternalNetworking.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(InternalNetworking.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 = InternalNetworking.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));
    return Observable.create(new ANOnSubscribe<T>(request));
}
Also used : Response(okhttp3.Response) ANResponse(com.androidnetworking.common.ANResponse) OkHttpClient(okhttp3.OkHttpClient) GET(com.androidnetworking.common.Method.GET) PUT(com.androidnetworking.common.Method.PUT) POST(com.androidnetworking.common.Method.POST) Request(okhttp3.Request) IOException(java.io.IOException) ResponseProgressBody(com.androidnetworking.internal.ResponseProgressBody) Interceptor(okhttp3.Interceptor)

Example 49 with Interceptor

use of com.pushtorefresh.storio3.Interceptor in project drill by apache.

the class SimpleHttp method setupHttpClient.

/**
 * Configures the OkHTTP3 server object with configuration info from the user.
 *
 * @return OkHttpClient configured server
 */
private OkHttpClient setupHttpClient() {
    Builder builder = new OkHttpClient.Builder();
    // Set up the HTTP Cache.   Future possibilities include making the cache size and retention configurable but
    // right now it is on or off.  The writer will write to the Drill temp directory if it is accessible and
    // output a warning if not.
    HttpStoragePluginConfig config = scanDefn.tableSpec().config();
    if (config.cacheResults()) {
        setupCache(builder);
    }
    HttpApiConfig apiConfig = scanDefn.tableSpec().connectionConfig();
    // If OAuth information is provided, we will assume that the user does not want to use
    // basic authentication
    HttpOAuthConfig oAuthConfig = scanDefn.tableSpec().config().oAuthConfig();
    if (oAuthConfig != null) {
        // Add interceptors for OAuth2
        logger.debug("Adding OAuth2 Interceptor");
        AccessTokenRepository repository = new AccessTokenRepository(proxyConfig, config, tokenTable);
        builder.authenticator(new AccessTokenAuthenticator(repository));
        builder.addInterceptor(new AccessTokenInterceptor(repository));
    } else if (apiConfig.authType().equalsIgnoreCase("basic")) {
        // If the API uses basic authentication add the authentication code.
        logger.debug("Adding Interceptor");
        UsernamePasswordCredentials credentials = apiConfig.getUsernamePasswordCredentials();
        builder.addInterceptor(new BasicAuthInterceptor(credentials.getUsername(), credentials.getPassword()));
    }
    // Set timeouts
    int timeout = Math.max(1, config.timeout());
    builder.connectTimeout(timeout, TimeUnit.SECONDS);
    builder.writeTimeout(timeout, TimeUnit.SECONDS);
    builder.readTimeout(timeout, TimeUnit.SECONDS);
    // Sourced from https://stackoverflow.com/questions/60110848/how-to-disable-ssl-verification
    if (!apiConfig.verifySSLCert()) {
        try {
            TrustManager[] trustAllCerts = getAllTrustingTrustManager();
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            HostnameVerifier verifier = (hostname, session) -> true;
            builder.hostnameVerifier(verifier);
        } catch (KeyManagementException | NoSuchAlgorithmException e) {
            logger.error("Error when configuring Drill not to verify SSL certs. {}", e.getMessage());
        }
    }
    // Set the proxy configuration
    addProxyInfo(builder, proxyConfig);
    return builder.build();
}
Also used : HttpSubScan(org.apache.drill.exec.store.http.HttpSubScan) X509Certificate(java.security.cert.X509Certificate) SSLContext(javax.net.ssl.SSLContext) Cache(okhttp3.Cache) URLDecoder(java.net.URLDecoder) UserException(org.apache.drill.common.exceptions.UserException) LoggerFactory(org.slf4j.LoggerFactory) TrustManager(javax.net.ssl.TrustManager) HttpOAuthConfig(org.apache.drill.exec.store.http.HttpOAuthConfig) StringUtils(org.apache.commons.lang3.StringUtils) FormBody(okhttp3.FormBody) PersistentTokenTable(org.apache.drill.exec.oauth.PersistentTokenTable) Matcher(java.util.regex.Matcher) Proxy(java.net.Proxy) Map(java.util.Map) HostnameVerifier(javax.net.ssl.HostnameVerifier) Interceptor(okhttp3.Interceptor) Request(okhttp3.Request) HttpMethod(org.apache.drill.exec.store.http.HttpApiConfig.HttpMethod) HttpApiConfig(org.apache.drill.exec.store.http.HttpApiConfig) KeyManagementException(java.security.KeyManagementException) Credentials(okhttp3.Credentials) InetSocketAddress(java.net.InetSocketAddress) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) AccessTokenAuthenticator(org.apache.drill.exec.store.http.oauth.AccessTokenAuthenticator) Objects(java.util.Objects) List(java.util.List) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) AccessTokenInterceptor(org.apache.drill.exec.store.http.oauth.AccessTokenInterceptor) Pattern(java.util.regex.Pattern) HttpUrl(okhttp3.HttpUrl) NotNull(org.jetbrains.annotations.NotNull) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Builder(okhttp3.OkHttpClient.Builder) StoragePluginRegistry(org.apache.drill.exec.store.StoragePluginRegistry) CustomErrorContext(org.apache.drill.common.exceptions.CustomErrorContext) ArrayList(java.util.ArrayList) UsernamePasswordCredentials(org.apache.drill.exec.store.security.UsernamePasswordCredentials) AccessTokenRepository(org.apache.drill.exec.store.http.oauth.AccessTokenRepository) Response(okhttp3.Response) Logger(org.slf4j.Logger) IOException(java.io.IOException) CaseInsensitiveMap(org.apache.drill.common.map.CaseInsensitiveMap) Paginator(org.apache.drill.exec.store.http.paginator.Paginator) File(java.io.File) TimeUnit(java.util.concurrent.TimeUnit) OkHttpClient(okhttp3.OkHttpClient) X509TrustManager(javax.net.ssl.X509TrustManager) HttpStoragePluginConfig(org.apache.drill.exec.store.http.HttpStoragePluginConfig) InputStream(java.io.InputStream) AccessTokenInterceptor(org.apache.drill.exec.store.http.oauth.AccessTokenInterceptor) HttpApiConfig(org.apache.drill.exec.store.http.HttpApiConfig) Builder(okhttp3.OkHttpClient.Builder) AccessTokenRepository(org.apache.drill.exec.store.http.oauth.AccessTokenRepository) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyManagementException(java.security.KeyManagementException) UsernamePasswordCredentials(org.apache.drill.exec.store.security.UsernamePasswordCredentials) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) HostnameVerifier(javax.net.ssl.HostnameVerifier) HttpOAuthConfig(org.apache.drill.exec.store.http.HttpOAuthConfig) AccessTokenAuthenticator(org.apache.drill.exec.store.http.oauth.AccessTokenAuthenticator) HttpStoragePluginConfig(org.apache.drill.exec.store.http.HttpStoragePluginConfig) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 50 with Interceptor

use of com.pushtorefresh.storio3.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

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