okgo Learning Notes: Global Configuration

#okgo Learning Notes (1): Global Configuration

Role: Note use.Original Detailed Development Document Address: https://github.com/jeasonlzy/okhttp-OkGo/wiki/Init

Initialization method

Typically configured in Aplication or base class, it only needs to be called once

  • log switch can be configured
  • Global timeout
  • Global cookie management policy
  • Https Configuration
  • Timeout Reconnection Number
  • Common information such as request headers and request parameters

1. The simplest configuration

OkGo.getInstance().init(this);

This is to use OkHttpClient, which is initialized by default inside OkGO, to make network requests. It contains basic log printing, timeout and https-related configuration. However, it is better to configure OkHttpClient to pass it to OkGO by yourself. The way to customize OkHttpClient in detail is to configure native okhttp.Some of the configurations below are optional, and you can add them if you need them or not.

2. Build OkHttpClient.Builder

OkHttpClient.Builder builder = new OkHttpClient.Builder();

3. Configure log

You can use OkGo's built-in log interceptor to print a log, and if you find it unusable, you can also write your own, which is unlimited.

HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
//Log Printing Level, which determines how detailed the log is displayed 
loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
//Log color level, which determines the color of the log displayed in the console
loggingInterceptor.setColorLevel(Level.INFO);
builder.addInterceptor(loggingInterceptor);

4. Configure timeout

The default timeout is 60 seconds

//Global Read Timeout
builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); 
//Global write timeout
builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);    
//Global connection timeout
builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS); 

5. Configure cookies so that you can choose one of the following

If you use persistence of cookies or the maintenance of Session s, then it is recommended to configure a cookie, which can also be customized, not necessarily using OkGos own. The following three are the three default ways provided by OkGos, you can choose to add, or you can implement the interface of CookieJar and manage the cookies yourself.

//Use sp to keep cookie s valid until they expire
builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));  
//Use database to keep cookie s valid until they expire
builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));
//Keep cookie s in memory and disappear after app exits
builder.cookieJar(new CookieJarImpl(new MemoryCookieStore())); 

6. Https configuration, the following options are set up on your own

This is also customizable. HttpsUtils is only a tool class provided in the framework to manage Https easily. You can also implement it yourself, preferably by passing an sslSocketFactory to OkHttpClient.Builder.

//Method 1: Trust all certificates, unsafe and risky
HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//Method 2: Customize the trust rules and verify the server side certificates
HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
//Method 3: Use the embedded certificate to verify the server certificate (self-signed certificate)
HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
//Method 4: Use bks certificate and password management client certificate (two-way authentication), use embedded certificate, verify service-side certificate (self-signed certificate)
HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//Configure the domain name matching rules for https, take a closer look at demo's initial introduction, don't join unless you need to, inappropriate use will cause HTTPS handshake to fail
builder.hostnameVerifier(new SafeHostnameVerifier());

7. Configure OkGo

//------------ Here's a sample code that tells you that you can do this. In practice, when you use it, you can do it as needed without passing it on ---------//
HttpHeaders headers = new HttpHeaders();
headers.put("commonHeaderKey1", "commonHeaderValue1");    //header does not support Chinese, special characters are not allowed
headers.put("commonHeaderKey2", "commonHeaderValue2");
HttpParams params = new HttpParams();
params.put("commonParamsKey1", "commonParamsValue1");     //param supports Chinese, pass directly, do not code by yourself
params.put("commonParamsKey2", "Chinese parameters are supported here");
//-------------------------------------------------------------------------------------//

OkGo.getInstance().init(this)                       //Initialization must be called
    .setOkHttpClient(builder.build())               //OkHttpClient is recommended. If not, the default will be used
    .setCacheMode(CacheMode.NO_CACHE)               //Global Unified Cache mode. Cache is not used by default and can not be passed
    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //Global Unified Cache Time, default never expires, can not pass
    .setRetryCount(3)                               //Global Unified Timeout Reconnection Number, defaulted to three times, then the worst case would be four requests (one original request, three reconnection requests), which does not need to be set to zero
    .addCommonHeaders(headers)                      //Global Common Header
    .addCommonParams(params);                       //Global Common Parameters

Keywords: OkHttp github network Session

Added by oshecho on Mon, 12 Aug 2019 04:59:16 +0300