Search in sources :

Example 36 with HttpLoggingInterceptor

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

the class Example11 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().addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())).addConverterFactory(GsonConverterFactory.create()).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) AndroidSchedulers(rx.android.schedulers.AndroidSchedulers) Action1(rx.functions.Action1) Observable(rx.Observable) Toast(android.widget.Toast) Map(java.util.Map) GsonConverterFactory(retrofit2.converter.gson.GsonConverterFactory) Schedulers(rx.schedulers.Schedulers) View(android.view.View) AdapterView(android.widget.AdapterView) ActionBar(android.app.ActionBar) Subscriber(rx.Subscriber) LayoutInflater(android.view.LayoutInflater) Expose(com.google.gson.annotations.Expose) 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) GET(retrofit2.http.GET) RxJavaCallAdapterFactory(retrofit2.adapter.rxjava.RxJavaCallAdapterFactory) Path(retrofit2.http.Path) ListView(android.widget.ListView) Activity(android.app.Activity) Retrofit(retrofit2.Retrofit) OkHttpClient(okhttp3.OkHttpClient) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor)

Example 37 with HttpLoggingInterceptor

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

the class Example15 method onCreate.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_example15);
    editText = (EditText) findViewById(R.id.editText1);
    if (Secrets.API_KEY.length() < 10) {
        Toast.makeText(this, "API KEY is unset!", Toast.LENGTH_LONG).show();
        return;
    }
    if (mGooglePlacesClient == null) {
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient client = new OkHttpClient.Builder().addInterceptor(loggingInterceptor).build();
        mGooglePlacesClient = new Retrofit.Builder().addCallAdapterFactory(RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io())).addConverterFactory(GsonConverterFactory.create(new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create())).baseUrl(GOOGLE_API_BASE_URL).client(client).build().create(GooglePlacesClient.class);
    }
    RxTextView.textChanges(editText).debounce(DELAY, TimeUnit.MILLISECONDS).map(new Func1<CharSequence, String>() {

        @Override
        public String call(CharSequence charSequence) {
            return charSequence.toString();
        }
    }).flatMap(new Func1<String, Observable<PlacesResult>>() {

        @Override
        public Observable<PlacesResult> call(String s) {
            Observable<PlacesResult> placesResult = null;
            try {
                placesResult = mGooglePlacesClient.autocomplete(Secrets.API_KEY, URLEncoder.encode(s, "utf8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            return placesResult;
        }
    }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<PlacesResult>() {

        @Override
        public void call(PlacesResult placesResult) {
            List<String> strings = new ArrayList<String>();
            for (Prediction p : placesResult.predictions) {
                strings.add(p.description);
            }
            ListView listView = (ListView) findViewById(R.id.listView1);
            if (listView != null) {
                listView.setAdapter(new ArrayAdapter<String>(Example15.this, android.R.layout.simple_list_item_1, strings));
            }
        }
    }, new Action1<Throwable>() {

        @Override
        public void call(Throwable throwable) {
            throwable.printStackTrace();
        }
    });
}
Also used : OkHttpClient(okhttp3.OkHttpClient) GsonBuilder(com.google.gson.GsonBuilder) GsonBuilder(com.google.gson.GsonBuilder) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Observable(rx.Observable) Retrofit(retrofit2.Retrofit) ListView(android.widget.ListView) ArrayList(java.util.ArrayList) List(java.util.List) Func1(rx.functions.Func1) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) ArrayAdapter(android.widget.ArrayAdapter)

Example 38 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project jianshi by wingjay.

the class AppModule method provideOkHttpClient.

@Provides
@Singleton
OkHttpClient provideOkHttpClient(GlobalRequestInterceptor globalRequestInterceptor) {
    OkHttpClient.Builder builder = new OkHttpClient.Builder().connectionPool(new ConnectionPool(5, 59, TimeUnit.SECONDS)).connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).addInterceptor(globalRequestInterceptor).retryOnConnectionFailure(false);
    if (BuildConfig.DEBUG) {
        builder.addNetworkInterceptor(new StethoInterceptor());
    }
    HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
    httpLoggingInterceptor.setLevel(BuildConfig.DEBUG ? HttpLoggingInterceptor.Level.BODY : HttpLoggingInterceptor.Level.NONE);
    builder.addInterceptor(httpLoggingInterceptor);
    return builder.build();
}
Also used : ConnectionPool(okhttp3.ConnectionPool) OkHttpClient(okhttp3.OkHttpClient) StethoInterceptor(com.facebook.stetho.okhttp3.StethoInterceptor) HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

Example 39 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project smartmodule by carozhu.

the class OkHttpUtils method getInstance.

public static OkHttpClient.Builder getInstance(final Context 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));
                if (ConfigureManager.getConfigureManager().isOkhttpLogger()) {
                    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 40 with HttpLoggingInterceptor

use of okhttp3.logging.HttpLoggingInterceptor in project u2020 by JakeWharton.

the class DebugApiModule method provideLoggingInterceptor.

@Provides
@Singleton
HttpLoggingInterceptor provideLoggingInterceptor() {
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(message -> Timber.tag("OkHttp").v(message));
    loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.HEADERS);
    return loggingInterceptor;
}
Also used : HttpLoggingInterceptor(okhttp3.logging.HttpLoggingInterceptor) Singleton(javax.inject.Singleton) Provides(dagger.Provides)

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