Search in sources :

Example 81 with OkHttpClient

use of okhttp3.OkHttpClient in project WordPress-Android by wordpress-mobile.

the class GravatarApi method createClient.

private static OkHttpClient createClient(final String accessToken) {
    OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
    //// uncomment the following line to add logcat logging
    //httpClientBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY));
    // add oAuth token usage
    httpClientBuilder.addInterceptor(new Interceptor() {

        @Override
        public Response intercept(Interceptor.Chain chain) throws IOException {
            Request original = chain.request();
            Request.Builder requestBuilder = original.newBuilder().header("Authorization", "Bearer " + accessToken).method(original.method(), original.body());
            Request request = requestBuilder.build();
            return chain.proceed(request);
        }
    });
    return httpClientBuilder.build();
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 82 with OkHttpClient

use of okhttp3.OkHttpClient in project Retrofit-Android-Basic by basil2style.

the class ServiceGenerator method createService.

public static <S> S createService(Class<S> serviceClass, final String authToken) {
    if (authToken != null) {
        httpClient.interceptors().add(new Interceptor() {

            @Override
            public okhttp3.Response intercept(Interceptor.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);
            }
        });
    }
    OkHttpClient client = httpClient.build();
    Retrofit retrofit = builder.client(client).build();
    return retrofit.create(serviceClass);
}
Also used : Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) IOException(java.io.IOException) Interceptor(okhttp3.Interceptor)

Example 83 with OkHttpClient

use of okhttp3.OkHttpClient in project BBS-Android by bdpqchen.

the class RxDoHttpClient method getUnsafeOkHttpClient.

public static OkHttpClient.Builder getUnsafeOkHttpClient() {
    try {
        // Create a trust manager that does not validate certificate chains
        final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[] {};
            }
        } };
        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("SSL");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        okHttpClient.sslSocketFactory(sslSocketFactory);
        okHttpClient.protocols(Collections.singletonList(Protocol.HTTP_1_1));
        okHttpClient.hostnameVerifier((hostname, session) -> true);
        return okHttpClient;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) SSLContext(javax.net.ssl.SSLContext) CertificateException(java.security.cert.CertificateException) TrustManager(javax.net.ssl.TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) X509TrustManager(javax.net.ssl.X509TrustManager) SSLSocketFactory(javax.net.ssl.SSLSocketFactory)

Example 84 with OkHttpClient

use of okhttp3.OkHttpClient in project smartmodule by carozhu.

the class OkHttpUtils method getInstance.

public static OkHttpClient.Builder getInstance(final Context context) {
    mcontext = context;
    if (singleton == null) {
        synchronized (OkHttpUtils.class) {
            if (singleton == null) {
                singleton = new OkHttpClient().newBuilder();
                singleton.connectTimeout(HTTP_CONNECT_TIMEOUT, TimeUnit.SECONDS);
                singleton.readTimeout(HTTP_READ_TIMEOUT, TimeUnit.SECONDS);
                //okhttp设置错误重新连接
                singleton.retryOnConnectionFailure(true);
                //singleton.addNetworkInterceptor(REWRITE_RESPONSE_INTERCEPTOR);
                //singleton.addInterceptor(REWRITE_RESPONSE_INTERCEPTOR_OFFLINE);
                File cacheDir = new File(context.getCacheDir(), RESPONSE_CACHE);
                singleton.cache(new Cache(cacheDir, RESPONSE_CACHE_SIZE));
                //or use
                //Cache cache = new Cache(context.getCacheDir(), RESPONSE_CACHE_SIZE);
                //singleton.cache(cache);
                //singleton.interceptors().add(new ReceivedCookiesInterceptor(context));
                //singleton.interceptors().add(new AddCookiesInterceptor(context));
                //singleton.addNetworkInterceptor(mTokenInterceptor)
                //addNetworkInterceptor 让所有网络请求都附上你的拦截器,
                //如这里设置了一个 token 拦截器,就是在所有网络请求的 header 加上 token 参数,下面会稍微讲一下这个内容
                HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
                interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
                singleton.addInterceptor(interceptor);
                if (ConfigureManager.getConfigureManager().isOkhttpCache()) {
                    //设置缓存路径
                    File httpCacheDirectory = new File(context.getCacheDir(), "httpCacheResponses");
                    //设置缓存 100M
                    Cache cache = new Cache(httpCacheDirectory, RESPONSE_CACHE_SIZE);
                    Interceptor myinterceptor = new Interceptor() {

                        @Override
                        public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
                            Log.i(TAG, "request=" + request);
                            if (!NetworkUtil.isNetworkAvailable(context)) {
                                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                                Log.i(TAG, "no network");
                            }
                            Response response = chain.proceed(request);
                            if (NetworkUtil.isNetworkAvailable(context)) {
                                // 有网络时 设置缓存超时时间0个小时
                                int maxAge = 0 * 60;
                                Log.i(TAG, "has network maxAge=" + maxAge);
                                response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).removeHeader(// 清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效
                                "Pragma").build();
                            } else {
                                Log.i(TAG, "network error");
                                // 无网络时,设置超时为4周
                                int maxStale = 60 * 60 * 24 * 28;
                                Log.i(TAG, "has maxStale=" + maxStale);
                                response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).removeHeader("Pragma").build();
                                Log.i(TAG, "response build maxStale=" + maxStale);
                            }
                            return response;
                        }
                    };
                    singleton.addInterceptor(myinterceptor).cache(cache);
                }
            }
        }
    }
    return singleton;
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) Request(okhttp3.Request) File(java.io.File) Interceptor(okhttp3.Interceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Example 85 with OkHttpClient

use of okhttp3.OkHttpClient in project chefly_android by chef-ly.

the class HttpConnection method downloadFromFeed.

public String downloadFromFeed(RequestMethod requestPackage) throws IOException {
    String address = requestPackage.getEndpoint();
    String encodedParams = requestPackage.getEncodedParams();
    //check for get request
    if (requestPackage.getMethod().equals("GET") && encodedParams.length() > 0) {
        address = String.format("%s?%s", address, encodedParams);
    }
    //create request object
    OkHttpClient client;
    if (BuildConfig.DEBUG) {
        client = new OkHttpClient.Builder().addInterceptor(new LoggingInterceptor()).build();
    } else {
        client = new OkHttpClient();
    }
    Request.Builder requestBuilder = new Request.Builder().url(address);
    //  Add required HTTP Header
    Map<String, String> headers = requestPackage.getHeaders();
    if (headers.size() > 0) {
        for (String k : headers.keySet()) {
            if (k != null) {
                requestBuilder.addHeader(k, headers.get(k));
            }
        }
    }
    //check for post request
    if (requestPackage.getMethod().equals("POST")) {
        //extract the parameters from the request
        //get the reference of the pair
        Map<String, String> params = requestPackage.getParams();
        String msg = "";
        if (params.size() == 1) {
            for (String key : params.keySet()) msg = params.get(key);
        } else {
            JSONObject parameter = new JSONObject(params);
            msg = parameter.toString();
        }
        RequestBody body = RequestBody.create(JSON, msg);
        Log.d(TAG, msg);
        requestBuilder.post(body);
        //requestBuilder.addHeader("content-type", "application/json; charset=utf-8");
        requestBuilder.addHeader("content-type", "application/x-www-form-urlencoded");
    }
    Request request = requestBuilder.build();
    //get response with the use of the method newCall
    //synchronous request
    Response response = client.newCall(request).execute();
    //check if the request is successful
    if (response.isSuccessful()) {
        this.statusMessage = response.message();
        return response.body().string();
    } else {
        Log.d(TAG, response.toString());
        throw new IOException("Exception: response code " + response.code());
    }
}
Also used : Response(okhttp3.Response) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) Request(okhttp3.Request) IOException(java.io.IOException) RequestBody(okhttp3.RequestBody)

Aggregations

OkHttpClient (okhttp3.OkHttpClient)149 Request (okhttp3.Request)73 Response (okhttp3.Response)61 IOException (java.io.IOException)52 Test (org.junit.Test)35 Call (okhttp3.Call)24 Retrofit (retrofit2.Retrofit)24 Interceptor (okhttp3.Interceptor)19 HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)18 MockResponse (okhttp3.mockwebserver.MockResponse)18 File (java.io.File)15 GsonBuilder (com.google.gson.GsonBuilder)12 Provides (dagger.Provides)12 SSLSocketFactory (javax.net.ssl.SSLSocketFactory)12 Gson (com.google.gson.Gson)10 ArrayList (java.util.ArrayList)10 List (java.util.List)10 Cache (okhttp3.Cache)10 Observable (rx.Observable)10 Singleton (javax.inject.Singleton)9