use of org.yh.library.okhttp.utils.HeaderInterceptor in project YhLibraryForAndroid by android-coco.
the class MyApplication method initHttp.
/**
* 初始化OKHTTP
*/
public static void initHttp() {
// 全局设置请求头 单独设置请求头覆盖全局设置
// Map<String, String> headers = new LinkedHashMap<>();
// headers.put("imei", "123123123");
// headers.put("version", "1.0");
// headers.put("token", "");
// headers.put("regid", "123123123");
// YHRequestFactory.getRequestManger().setHeaders(headers);
// 缓存http
// Cache cache = new Cache(new File(FileUtils.getSavePath(Constants.httpCachePath)), cacheSize);
// cookie
ClearableCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(getInstance()));
HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(null, null, null);
OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(60000L, TimeUnit.MILLISECONDS).readTimeout(60000L, TimeUnit.MILLISECONDS).writeTimeout(60000L, TimeUnit.MILLISECONDS).addInterceptor(// 日志拦截 是否显示返回数据
new LoggerInterceptor("", true)).addInterceptor(// 统一请求头
new HeaderInterceptor()).addNetworkInterceptor(new // 添加网络拦截器缓存用
Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Response response = chain.proceed(request);
if (NetWorkUtils.isConnectedByState(getInstance())) {
// 有网 就1个小时可用 缓存有效时间
int maxAge = 60 * 60;
return response.newBuilder().header("Cache-Control", "public, max-age=" + maxAge).build();
} else {
// 没网 就1周可用 缓存有效时间
int maxStale = 60 * 60 * 24 * 7;
return response.newBuilder().header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale).build();
}
}
}).hostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
}).cookieJar(cookieJar).sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager).build();
OkHttpUtils.initClient(okHttpClient);
}
Aggregations