Search in sources :

Example 31 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project AndroidFrame by tongxiaoyun.

the class m method initNetWorkWithCookie.

/**
 * 初始化网络控制器
 */
public m initNetWorkWithCookie(Context context) {
    // 持久化存储cookie
    ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(context));
    // log拦截器
    HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
    logging.setLevel(HttpLoggingInterceptor.Level.BODY);
    // 自定义OkHttp
    OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000L, TimeUnit.MILLISECONDS).readTimeout(10000L, TimeUnit.MILLISECONDS).cookieJar(// 设置开启cookie
    cookieJar).addInterceptor(// 设置开启log
    logging).build();
    netUtils = new MyOkHttp(okHttpClient);
    return instance;
}
Also used : MyOkHttp(com.risenb.expand.network.MyOkHttp) ClearableCookieJar(com.risenb.expand.network.cookie.ClearableCookieJar) OkHttpClient(okhttp3.OkHttpClient) PersistentCookieJar(com.risenb.expand.network.cookie.PersistentCookieJar) SetCookieCache(com.risenb.expand.network.cookie.cache.SetCookieCache) SharedPrefsCookiePersistor(com.risenb.expand.network.cookie.persistence.SharedPrefsCookiePersistor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 32 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project CloudReader by youlookwhat.

the class HttpUtils method getUnsafeOkHttpClient.

private OkHttpClient getUnsafeOkHttpClient() {
    try {
        // Install the all-trusting trust manager TLS
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new SecureRandom());
        // cache url
        File httpCacheDirectory = new File(context.getCacheDir(), "responses");
        // 50 MiB
        int cacheSize = 50 * 1024 * 1024;
        Cache cache = new Cache(httpCacheDirectory, cacheSize);
        // Create an ssl socket factory with our all-trusting manager
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        OkHttpClient.Builder okBuilder = new OkHttpClient.Builder();
        okBuilder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
        okBuilder.readTimeout(30, TimeUnit.SECONDS);
        okBuilder.connectTimeout(30, TimeUnit.SECONDS);
        okBuilder.writeTimeout(30, TimeUnit.SECONDS);
        okBuilder.addInterceptor(new HttpHeadInterceptor());
        // 持久化cookie
        okBuilder.addInterceptor(new ReceivedCookiesInterceptor(context));
        okBuilder.addInterceptor(new AddCookiesInterceptor(context));
        // 添加缓存,无网访问时会拿缓存,只会缓存get请求
        okBuilder.addInterceptor(new AddCacheInterceptor(context));
        okBuilder.cache(cache);
        okBuilder.addInterceptor(new HttpLoggingInterceptor().setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE));
        okBuilder.hostnameVerifier(new HostnameVerifier() {

            @SuppressLint("BadHostnameVerifier")
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        return okBuilder.build();
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) SSLSession(javax.net.ssl.SSLSession) SecureRandom(java.security.SecureRandom) SSLContext(javax.net.ssl.SSLContext) SuppressLint(android.annotation.SuppressLint) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) HostnameVerifier(javax.net.ssl.HostnameVerifier) SuppressLint(android.annotation.SuppressLint) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) File(java.io.File) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Cache(okhttp3.Cache)

Example 33 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor 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 34 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project okhttp by square.

the class EventListenerTest method successfulCallEventSequenceWithListener.

@Test
public void successfulCallEventSequenceWithListener() throws IOException {
    server.enqueue(new MockResponse().setBody("abc"));
    client = client.newBuilder().addNetworkInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build();
    Call call = client.newCall(new Request.Builder().url(server.url("/")).build());
    Response response = call.execute();
    assertThat(response.code()).isEqualTo(200);
    assertThat(response.body().string()).isEqualTo("abc");
    response.body().close();
    assertThat(listener.recordedEventTypes()).containsExactly("CallStart", "ProxySelectStart", "ProxySelectEnd", "DnsStart", "DnsEnd", "ConnectStart", "ConnectEnd", "ConnectionAcquired", "RequestHeadersStart", "RequestHeadersEnd", "ResponseHeadersStart", "ResponseHeadersEnd", "ResponseBodyStart", "ResponseBodyEnd", "ConnectionReleased", "CallEnd");
}
Also used : MockResponse(mockwebserver3.MockResponse) MockResponse(mockwebserver3.MockResponse) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Test(org.junit.jupiter.api.Test)

Example 35 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project AnDevCon-RxPatterns by colintheshots.

the class Example1_NoRX method createGithubClient.

private void createGithubClient() {
    if (mGitHubClient == null) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).addInterceptor(chain -> chain.proceed(chain.request().newBuilder().addHeader("Authorization", "token " + Secrets.GITHUB_PERSONAL_ACCESS_TOKEN).build())).build();
        mGitHubClient = new Retrofit.Builder().client(client).baseUrl(GITHUB_BASE_URL).build().create(GitHubClient.class);
    }
}
Also used : Context(android.content.Context) Iterables(com.google.common.collect.Iterables) Bundle(android.os.Bundle) LayoutInflater(android.view.LayoutInflater) Expose(com.google.gson.annotations.Expose) Response(retrofit2.Response) ViewGroup(android.view.ViewGroup) Retrofit(retrofit2.Retrofit) List(java.util.List) TextView(android.widget.TextView) OkHttpClient(okhttp3.OkHttpClient) BaseAdapter(android.widget.BaseAdapter) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Callback(retrofit2.Callback) GET(retrofit2.http.GET) Toast(android.widget.Toast) Map(java.util.Map) Path(retrofit2.http.Path) View(android.view.View) ListView(android.widget.ListView) Activity(android.app.Activity) Call(retrofit2.Call) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Aggregations

HttpLoggingInterceptor (okhttp3.logging.HttpLoggingInterceptor)118 OkHttpClient (okhttp3.OkHttpClient)98 Retrofit (retrofit2.Retrofit)34 GsonBuilder (com.google.gson.GsonBuilder)30 Provides (dagger.Provides)27 Singleton (javax.inject.Singleton)24 Cache (okhttp3.Cache)19 Request (okhttp3.Request)18 Response (okhttp3.Response)17 IOException (java.io.IOException)16 Gson (com.google.gson.Gson)15 File (java.io.File)15 Interceptor (okhttp3.Interceptor)11 InfoInterceptor (com.eveningoutpost.dexdrip.tidepool.InfoInterceptor)6 StethoInterceptor (com.facebook.stetho.okhttp3.StethoInterceptor)6 List (java.util.List)5 ErrorInterceptor (me.postaddict.instagram.scraper.interceptor.ErrorInterceptor)5 FakeBrowserInterceptor (me.postaddict.instagram.scraper.interceptor.FakeBrowserInterceptor)5 ResponseBody (okhttp3.ResponseBody)5 BeforeClass (org.junit.BeforeClass)5