com.lzy.okgo.cache.CacheMode Java Examples

The following examples show how to use com.lzy.okgo.cache.CacheMode. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BaseCachePolicy.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
/**
 * 请求成功后根据缓存模式,更新缓存数据
 *
 * @param headers 响应头
 * @param data    响应数据
 */
private void saveCache(Headers headers, T data) {
    if (data == null) {
        return;
    }
    if (request.getCacheMode() == CacheMode.NO_CACHE) return;    //不需要缓存,直接返回
    if (data instanceof Bitmap) return;             //Bitmap没有实现Serializable,不能缓存

    CacheEntity<T> cache = HeaderParser.createCacheEntity(headers, data, request.getCacheMode(), request.getCacheKey());
    if (cache == null) {
        //服务器不需要缓存,移除本地缓存
        CacheManager.getInstance().remove(request.getCacheKey());
    } else {
        //缓存命中,更新缓存
        CacheManager.getInstance().replace(request.getCacheKey(), cache);
    }
}
 
Example #2
Source File: VrVideoFragment.java    From GoogleVR with Apache License 2.0 6 votes vote down vote up
@Override
	public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//		super.onViewCreated(view, savedInstanceState);
		recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
		RecyclerView.LayoutManager layoutManager = getLayoutManager();
		recyclerView.setLayoutManager(layoutManager);

		OkGo.get(ApiUrls.URL_Query).cacheKey(ApiUrls.URL_Query).cacheMode(CacheMode.DEFAULT).execute(new StringCallback() {

			@Override
			public void onSuccess(String s, Call call, Response response) {
				try {
					JSONObject obj = new JSONObject(s);
					String content = obj.getString("content");
					List<VideoItem> videoItems = JSON.parseArray(content, VideoItem.class);
					recyclerView.setAdapter(new VrVideoAdapter(videoItems));
				} catch (JSONException e) {
					e.printStackTrace();
				}
			}
		});
	}
 
Example #3
Source File: OkGo.java    From BaseProject with Apache License 2.0 6 votes vote down vote up
private OkGo() {
    mDelivery = new Handler(Looper.getMainLooper());
    mRetryCount = 3;
    mCacheTime = CacheEntity.CACHE_NEVER_EXPIRE;
    mCacheMode = CacheMode.NO_CACHE;

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
    loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
    loggingInterceptor.setColorLevel(Level.CONFIG);
    builder.addInterceptor(loggingInterceptor);

    builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
    builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
    builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

    HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
    builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
    builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);
    okHttpClient = builder.build();
}
 
Example #4
Source File: OkGo.java    From okhttp-OkGo with Apache License 2.0 6 votes vote down vote up
private OkGo() {
    mDelivery = new Handler(Looper.getMainLooper());
    mRetryCount = 3;
    mCacheTime = CacheEntity.CACHE_NEVER_EXPIRE;
    mCacheMode = CacheMode.NO_CACHE;

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
    loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
    loggingInterceptor.setColorLevel(Level.INFO);
    builder.addInterceptor(loggingInterceptor);

    builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
    builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
    builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

    HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
    builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
    builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);
    okHttpClient = builder.build();
}
 
Example #5
Source File: BaseCachePolicy.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
/**
 * 请求成功后根据缓存模式,更新缓存数据
 *
 * @param headers 响应头
 * @param data    响应数据
 */
private void saveCache(Headers headers, T data) {
    if (request.getCacheMode() == CacheMode.NO_CACHE) return;    //不需要缓存,直接返回
    if (data instanceof Bitmap) return;             //Bitmap没有实现Serializable,不能缓存

    CacheEntity<T> cache = HeaderParser.createCacheEntity(headers, data, request.getCacheMode(), request.getCacheKey());
    if (cache == null) {
        //服务器不需要缓存,移除本地缓存
        CacheManager.getInstance().remove(request.getCacheKey());
    } else {
        //缓存命中,更新缓存
        CacheManager.getInstance().replace(request.getCacheKey(), cache);
    }
}
 
Example #6
Source File: ComputerNewsFragment.java    From MyHearts with Apache License 2.0 5 votes vote down vote up
private void setHeaderView() {
    View headerView = LayoutInflater.from(getContext())
            .inflate(R.layout.news_banner_item_layout, null);
    mFlyBanner = (FlyBanner) headerView.findViewById(R.id.fly_banner);
    OkGo.get(bannerUrl)
            .tag(this)
            .cacheMode(CacheMode.DEFAULT)
            .execute(new StringCallback() {

                @Override
                public void onSuccess(String s, Call call, Response response) {
                    Type type = new TypeToken<NewsBannerBean>() {
                    }.getType();
                    NewsBannerBean bannerBean = new Gson().fromJson(s, type);
                    if (bannerBean.getCount() > 0) {
                        List<String> imgBanner = new ArrayList<>();
                        for (NewsBannerBean.DatasEntity entity : bannerBean.getDatas()) {
                            imgBanner.add(entity.getHeadPicUrl());
                        }
                        mFlyBanner.setImagesUrl(imgBanner);
                        mFlyBanner.setOnItemClickListener(position -> {
                            String id = bannerBean.getDatas().get(position).getId();
                            Intent intent = new Intent(getActivity(), NewsDetailActivity.class);
                            intent.putExtra("id", id);
                            intent.putExtra(Contants.TITLE, title);
                            startActivity(intent);
                        });
                    }
                }
            });
    mNewsAdapter.setHeaderView(headerView);

}
 
Example #7
Source File: CacheActivity.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.first_cache_then_request)
public void first_cache_then_request(View view) {
    OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
            .tag(this)//
            .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)//
            .cacheKey("first_cache_then_request")//
            .cacheTime(5000)            // 单位毫秒.5秒后过期
            .headers("header1", "headerValue1")//
            .params("param1", "paramValue1")//
            .execute(new CacheCallBack(this));
}
 
Example #8
Source File: CacheActivity.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.if_none_cache_request)
public void if_none_cache_request(View view) {
    OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
            .tag(this)//
            .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)//
            .cacheKey("if_none_cache_request")//
            .cacheTime(5000)            // 单位毫秒.5秒后过期
            .headers("header1", "headerValue1")//
            .params("param1", "paramValue1")//
            .execute(new CacheCallBack(this));
}
 
Example #9
Source File: CacheActivity.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.request_failed_read_cache)
public void request_failed_read_cache(View view) {
    OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
            .tag(this)//
            .cacheMode(CacheMode.REQUEST_FAILED_READ_CACHE)//
            .cacheKey("request_failed_read_cache")//
            .cacheTime(5000)            // 单位毫秒.5秒后过期
            .headers("header1", "headerValue1")//
            .params("param1", "paramValue1")//
            .execute(new CacheCallBack(this));
}
 
Example #10
Source File: CacheActivity.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.cache_default)
public void cache_default(View view) {
    OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
            .tag(this)//
            .cacheMode(CacheMode.DEFAULT)//
            .cacheKey("cache_default")//
            .cacheTime(5000)//对于默认的缓存模式,该时间无效,依靠的是服务端对304缓存的控制
            .headers("header1", "headerValue1")//
            .params("param1", "paramValue1")//
            .execute(new CacheCallBack(this));
}
 
Example #11
Source File: CacheActivity.java    From okhttp-OkGo with Apache License 2.0 5 votes vote down vote up
@OnClick(R.id.no_cache)
public void no_cache(View view) {
    OkGo.<LzyResponse<ServerModel>>get(Urls.URL_CACHE)//
            .tag(this)//
            .cacheMode(CacheMode.NO_CACHE)//
            .cacheKey("no_cache")   //对于无缓存模式,该参数无效
            .cacheTime(5000)        //对于无缓存模式,该时间无效
            .headers("header1", "headerValue1")//
            .params("param1", "paramValue1")//
            .execute(new CacheCallBack(this));
}
 
Example #12
Source File: MyApplication.java    From GoogleVR with Apache License 2.0 5 votes vote down vote up
@Override
public void onCreate() {
	super.onCreate();
	//全局初始化
	OkGo.init(this);
	OkGo.getInstance().setConnectTimeout(3000)
			.setReadTimeOut(3000)
			.setWriteTimeOut(3000)
			.setCacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
			.setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
			.setRetryCount(3);
}
 
Example #13
Source File: Request.java    From BaseProject with Apache License 2.0 4 votes vote down vote up
public CacheMode getCacheMode() {
    return cacheMode;
}
 
Example #14
Source File: OkGo.java    From BaseProject with Apache License 2.0 4 votes vote down vote up
/** 获取全局的缓存模式 */
public CacheMode getCacheMode() {
    return mCacheMode;
}
 
Example #15
Source File: OkGo.java    From BaseProject with Apache License 2.0 4 votes vote down vote up
/** 全局的缓存模式 */
public OkGo setCacheMode(CacheMode cacheMode) {
    mCacheMode = cacheMode;
    return this;
}
 
Example #16
Source File: HeaderParser.java    From BaseProject with Apache License 2.0 4 votes vote down vote up
/**
 * 根据请求结果生成对应的缓存实体类,以下为缓存相关的响应头
 * Cache-Control: public                             响应被缓存,并且在多用户间共享
 * Cache-Control: private                            响应只能作为私有缓存,不能在用户之间共享
 * Cache-Control: no-cache                           提醒浏览器要从服务器提取文档进行验证
 * Cache-Control: no-store                           绝对禁止缓存(用于机密,敏感文件)
 * Cache-Control: max-age=60                         60秒之后缓存过期(相对时间),优先级比Expires高
 * Date: Mon, 19 Nov 2012 08:39:00 GMT               当前response发送的时间
 * Expires: Mon, 19 Nov 2012 08:40:01 GMT            缓存过期的时间(绝对时间)
 * Last-Modified: Mon, 19 Nov 2012 08:38:01 GMT      服务器端文件的最后修改时间
 * ETag: "20b1add7ec1cd1:0"                          服务器端文件的ETag值
 * 如果同时存在cache-control和Expires,浏览器总是优先使用cache-control
 *
 * @param responseHeaders 返回数据中的响应头
 * @param data            解析出来的数据
 * @param cacheMode       缓存的模式
 * @param cacheKey        缓存的key
 * @return 缓存的实体类
 */
public static <T> CacheEntity<T> createCacheEntity(Headers responseHeaders, T data, CacheMode cacheMode, String cacheKey) {

    long localExpire = 0;   // 缓存相对于本地的到期时间

    if (cacheMode == CacheMode.DEFAULT) {
        long date = HttpHeaders.getDate(responseHeaders.get(HttpHeaders.HEAD_KEY_DATE));
        long expires = HttpHeaders.getExpiration(responseHeaders.get(HttpHeaders.HEAD_KEY_EXPIRES));
        String cacheControl = HttpHeaders.getCacheControl(responseHeaders.get(HttpHeaders.HEAD_KEY_CACHE_CONTROL), responseHeaders.get(HttpHeaders.HEAD_KEY_PRAGMA));

        //没有缓存头控制,不需要缓存
        if (TextUtils.isEmpty(cacheControl) && expires <= 0) return null;

        long maxAge = 0;
        if (!TextUtils.isEmpty(cacheControl)) {
            StringTokenizer tokens = new StringTokenizer(cacheControl, ",");
            while (tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim().toLowerCase(Locale.getDefault());
                if (token.equals("no-cache") || token.equals("no-store")) {
                    //服务器指定不缓存
                    return null;
                } else if (token.startsWith("max-age=")) {
                    try {
                        //获取最大缓存时间
                        maxAge = Long.parseLong(token.substring(8));
                        //服务器缓存设置立马过期,不缓存
                        if (maxAge <= 0) return null;
                    } catch (Exception e) {
                        OkLogger.printStackTrace(e);
                    }
                }
            }
        }

        //获取基准缓存时间,优先使用response中的date头,如果没有就使用本地时间
        long now = System.currentTimeMillis();
        if (date > 0) now = date;

        if (maxAge > 0) {
            // Http1.1 优先验证 Cache-Control 头
            localExpire = now + maxAge * 1000;
        } else if (expires >= 0) {
            // Http1.0 验证 Expires 头
            localExpire = expires;
        }
    } else {
        localExpire = System.currentTimeMillis();
    }

    //将response中所有的头存入 HttpHeaders,原因是写入数据库的对象需要实现序列化,而ok默认的Header没有序列化
    HttpHeaders headers = new HttpHeaders();
    for (String headerName : responseHeaders.names()) {
        headers.put(headerName, responseHeaders.get(headerName));
    }

    //构建缓存实体对象
    CacheEntity<T> cacheEntity = new CacheEntity<>();
    cacheEntity.setKey(cacheKey);
    cacheEntity.setData(data);
    cacheEntity.setLocalExpire(localExpire);
    cacheEntity.setResponseHeaders(headers);
    return cacheEntity;
}
 
Example #17
Source File: MyApplication.java    From MyHearts with Apache License 2.0 4 votes vote down vote up
@Override
    public void onCreate() {
        super.onCreate();

        mInstance = this;

        dbManager = new DBManager(getApplicationContext());
        dbManager.openDatabase();

        NineGridView.setImageLoader(new PicassoImageLoader());

        Bmob.initialize(this, "6d7ed6a006f2606890427bf70345cdb9");

        if (flag == true) {
            flag = false;
            BmobUpdateAgent.initAppVersion();
        }

        JPushInterface.init(this);            // 初始化 JPush


        //短信验证

        SMSSDK.initSDK(this, ManifestUtil.getMetaDataValue(this, "mob_sms_appKey"),
                ManifestUtil.getMetaDataValue(this, "mob_sms_appSecrect"));


        OkGo.init(this);

        //以下设置的所有参数是全局参数,同样的参数可以在请求的时候再设置一遍,那么对于该请求来讲,请求中的参数会覆盖全局参数
        //好处是全局参数统一,特定请求可以特别定制参数
        try {
            //以下都不是必须的,根据需要自行选择,一般来说只需要 debug,缓存相关,cookie相关的 就可以了
            OkGo.getInstance()

                    //打开该调试开关,控制台会使用 红色error 级别打印log,并不是错误,是为了显眼,不需要就不要加入该行
                    .debug("OkGo")

                    //如果使用默认的 60秒,以下三行也不需要传
                    .setConnectTimeout(OkGo.DEFAULT_MILLISECONDS)  //全局的连接超时时间
                    .setReadTimeOut(OkGo.DEFAULT_MILLISECONDS)     //全局的读取超时时间
                    .setWriteTimeOut(OkGo.DEFAULT_MILLISECONDS)    //全局的写入超时时间

                    //可以全局统一设置缓存模式,默认是不使用缓存,可以不传,具体其他模式看 github 介绍 https://github.com/jeasonlzy0216/
                    .setCacheMode(CacheMode.NO_CACHE)

                    //可以全局统一设置缓存时间,默认永不过期,具体使用方法看 github 介绍
                    .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)

                    //如果不想让框架管理cookie,以下不需要
//                .setCookieStore(new MemoryCookieStore())                //cookie使用内存缓存(app退出后,cookie消失)
                    .setCookieStore(new PersistentCookieStore());        //cookie持久化存储,如果cookie不过期,则一直有效

            //可以设置https的证书,以下几种方案根据需要自己设置
//                    .setCertificates()                                  //方法一:信任所有证书(选一种即可)
//                    .setCertificates(getAssets().open("srca.cer"))      //方法二:也可以自己设置https证书(选一种即可)
//                    .setCertificates(getAssets().open("aaaa.bks"), "123456", getAssets().open("srca.cer"))//方法三:传入bks证书,密码,和cer证书,支持双向加密

            //可以添加全局拦截器,不会用的千万不要传,错误写法直接导致任何回调不执行
//                .addInterceptor(new Interceptor() {
//                    @Override
//                    public Response intercept(Chain chain) throws IOException {
//                        return chain.proceed(chain.request());
//                    }
//                })

            //这两行同上,不需要就不要传
            // .addCommonHeaders(headers)                                         //设置全局公共头
            // .addCommonParams(params);                                          //设置全局公共参数
        } catch (Exception e) {
            e.printStackTrace();
        }
        // initUser();
        //  Fresco.initialize(this);

//ID1105704769

        //    mTencent = Tencent.createInstance("1105704769", this);


    }
 
Example #18
Source File: OkGo.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
/** 获取全局的缓存模式 */
public CacheMode getCacheMode() {
    return mCacheMode;
}
 
Example #19
Source File: HeaderParser.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
/**
 * 根据请求结果生成对应的缓存实体类,以下为缓存相关的响应头
 * Cache-Control: public                             响应被缓存,并且在多用户间共享
 * Cache-Control: private                            响应只能作为私有缓存,不能在用户之间共享
 * Cache-Control: no-cache                           提醒浏览器要从服务器提取文档进行验证
 * Cache-Control: no-store                           绝对禁止缓存(用于机密,敏感文件)
 * Cache-Control: max-age=60                         60秒之后缓存过期(相对时间),优先级比Expires高
 * Date: Mon, 19 Nov 2012 08:39:00 GMT               当前response发送的时间
 * Expires: Mon, 19 Nov 2012 08:40:01 GMT            缓存过期的时间(绝对时间)
 * Last-Modified: Mon, 19 Nov 2012 08:38:01 GMT      服务器端文件的最后修改时间
 * ETag: "20b1add7ec1cd1:0"                          服务器端文件的ETag值
 * 如果同时存在cache-control和Expires,浏览器总是优先使用cache-control
 *
 * @param responseHeaders 返回数据中的响应头
 * @param data            解析出来的数据
 * @param cacheMode       缓存的模式
 * @param cacheKey        缓存的key
 * @return 缓存的实体类
 */
public static <T> CacheEntity<T> createCacheEntity(Headers responseHeaders, T data, CacheMode cacheMode, String cacheKey) {

    long localExpire = 0;   // 缓存相对于本地的到期时间

    if (cacheMode == CacheMode.DEFAULT) {
        long date = HttpHeaders.getDate(responseHeaders.get(HttpHeaders.HEAD_KEY_DATE));
        long expires = HttpHeaders.getExpiration(responseHeaders.get(HttpHeaders.HEAD_KEY_EXPIRES));
        String cacheControl = HttpHeaders.getCacheControl(responseHeaders.get(HttpHeaders.HEAD_KEY_CACHE_CONTROL), responseHeaders.get(HttpHeaders.HEAD_KEY_PRAGMA));

        //没有缓存头控制,不需要缓存
        if (TextUtils.isEmpty(cacheControl) && expires <= 0) return null;

        long maxAge = 0;
        if (!TextUtils.isEmpty(cacheControl)) {
            StringTokenizer tokens = new StringTokenizer(cacheControl, ",");
            while (tokens.hasMoreTokens()) {
                String token = tokens.nextToken().trim().toLowerCase(Locale.getDefault());
                if (token.equals("no-cache") || token.equals("no-store")) {
                    //服务器指定不缓存
                    return null;
                } else if (token.startsWith("max-age=")) {
                    try {
                        //获取最大缓存时间
                        maxAge = Long.parseLong(token.substring(8));
                        //服务器缓存设置立马过期,不缓存
                        if (maxAge <= 0) return null;
                    } catch (Exception e) {
                        OkLogger.printStackTrace(e);
                    }
                }
            }
        }

        //获取基准缓存时间,优先使用response中的date头,如果没有就使用本地时间
        long now = System.currentTimeMillis();
        if (date > 0) now = date;

        if (maxAge > 0) {
            // Http1.1 优先验证 Cache-Control 头
            localExpire = now + maxAge * 1000;
        } else if (expires >= 0) {
            // Http1.0 验证 Expires 头
            localExpire = expires;
        }
    } else {
        localExpire = System.currentTimeMillis();
    }

    //将response中所有的头存入 HttpHeaders,原因是写入数据库的对象需要实现序列化,而ok默认的Header没有序列化
    HttpHeaders headers = new HttpHeaders();
    for (String headerName : responseHeaders.names()) {
        headers.put(headerName, responseHeaders.get(headerName));
    }

    //构建缓存实体对象
    CacheEntity<T> cacheEntity = new CacheEntity<>();
    cacheEntity.setKey(cacheKey);
    cacheEntity.setData(data);
    cacheEntity.setLocalExpire(localExpire);
    cacheEntity.setResponseHeaders(headers);
    return cacheEntity;
}
 
Example #20
Source File: Request.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
public CacheMode getCacheMode() {
    return cacheMode;
}
 
Example #21
Source File: OkGoUtils.java    From DevUtils with Apache License 2.0 4 votes vote down vote up
/**
     * 初始化 OkGo 配置
     * <pre>
     *     @see <a href="https://github.com/jeasonlzy/okhttp-OkGo/wiki/Init"/>
     *     tips: 最简单的配置直接调用 OkGo.getInstance().init(this); {@link OkGo}
     *     在 App {@link Application} 初始化
     * </pre>
     * @param application {@link Application}
     */
    public static void initOkGo(Application application) {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();

        // 自定义日志拦截 JSON 打印
        builder.addInterceptor(new dev.other.okgo.HttpLoggingInterceptor());

        // ========================
        // = OkGo 内置 log 拦截器 =
        // ========================

        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
        // log 打印级别, 决定了 log 显示的详细程度
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);
        // log 颜色级别, 决定了 log 在控制台显示的颜色
        loggingInterceptor.setColorLevel(Level.INFO);
        builder.addInterceptor(loggingInterceptor);

        // ===============
        // = 配置超时时间 =
        // ===============

        // 全局的读取超时时间
        builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        // 全局的写入超时时间
        builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);
        // 全局的连接超时时间
        builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);

        // =============================
        // = Cookie 持久化 ( Session ) =
        // =============================

        // 使用 sp 保持 cookie, 如果 cookie 不过期, 则一直有效
        builder.cookieJar(new CookieJarImpl(new SPCookieStore(application)));
//        // 使用数据库保持 cookie, 如果 cookie 不过期, 则一直有效
//        builder.cookieJar(new CookieJarImpl(new DBCookieStore(application)));
//        // 使用内存保持 cookie, app 退出后, cookie 消失
//        builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));

        // ==============
        // = Https 配置 =
        // ==============

//        // 方法一: 信任所有证书, 不安全有风险
//        HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
//        // 方法二: 自定义信任规则, 校验服务端证书
//        HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
//        // 方法三: 使用预埋证书, 校验服务端证书 ( 自签名证书 ) 
//        HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(application.getAssets().open("srca.cer"));
//        // 方法四: 使用 bks 证书和密码管理客户端证书 ( 双向认证 ) , 使用预埋证书, 校验服务端证书 ( 自签名证书 ) 
//        HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(application.getAssets().open("xxx.bks"),
//            "123456", application.getAssets().open("yyy.cer"));
//        builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
//        // 配置 https 的域名匹配规则, 详细看 demo 的初始化介绍, 不需要就不要加入, 使用不当会导致 https 握手失败
//        builder.hostnameVerifier(new SafeHostnameVerifier());

        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory();
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
        builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);

        // ===============
        // = 全局公共数据 =
        // ===============

        // header 不支持中文, 不允许有特殊字符
        HttpHeaders headers = new HttpHeaders();
        headers.put("commonHeaderKey1", "commonHeaderValue1");
        headers.put("commonHeaderKey2", "commonHeaderValue2");

        // param 支持中文, 直接传, 不要自己编码
        HttpParams params = new HttpParams();
        params.put("commonParamsKey1", "commonParamsValue1");
        params.put("commonParamsKey2", "这里支持中文参数");

        // =======================
        // = 初始化 ( 应用 ) 配置 =
        // =======================

        OkGo.getInstance().init(application)
                // 建议设置 OkHttpClient, 不设置将使用默认的
                .setOkHttpClient(builder.build())
                // 全局统一缓存模式, 默认不使用缓存, 可以不传
                .setCacheMode(CacheMode.NO_CACHE)
                // 全局统一缓存时间, 默认永不过期, 可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)
                // 全局统一超时重连次数, 默认为三次, 那么最差的情况会请求 4 次 ( 一次原始请求, 三次重连请求 ), 不需要可以设置为 0
                .setRetryCount(3)
                // 全局公共头
                .addCommonHeaders(headers)
                // 全局公共参数
                .addCommonParams(params);
    }
 
Example #22
Source File: OkGo.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
/** 全局的缓存模式 */
public OkGo setCacheMode(CacheMode cacheMode) {
    mCacheMode = cacheMode;
    return this;
}
 
Example #23
Source File: GApp.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
private void initOkGo() {
    //---------这里给出的是示例代码,告诉你可以这么传,实际使用的时候,根据需要传,不需要就不传-------------//
    HttpHeaders headers = new HttpHeaders();
    headers.put("commonHeaderKey1", "commonHeaderValue1");    //header不支持中文,不允许有特殊字符
    headers.put("commonHeaderKey2", "commonHeaderValue2");
    HttpParams params = new HttpParams();
    params.put("commonParamsKey1", "commonParamsValue1");     //param支持中文,直接传,不要自己编码
    params.put("commonParamsKey2", "这里支持中文参数");
    //----------------------------------------------------------------------------------------//

    OkHttpClient.Builder builder = new OkHttpClient.Builder();
    //log相关
    HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkGo");
    loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别,决定了log显示的详细程度
    loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别,决定了log在控制台显示的颜色
    builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
    //第三方的开源库,使用通知显示当前请求的log,不过在做文件下载的时候,这个库好像有问题,对文件判断不准确
    //builder.addInterceptor(new ChuckInterceptor(this));

    //超时时间设置,默认60秒
    builder.readTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);      //全局的读取超时时间
    builder.writeTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);     //全局的写入超时时间
    builder.connectTimeout(OkGo.DEFAULT_MILLISECONDS, TimeUnit.MILLISECONDS);   //全局的连接超时时间

    //自动管理cookie(或者叫session的保持),以下几种任选其一就行
    //builder.cookieJar(new CookieJarImpl(new SPCookieStore(this)));            //使用sp保持cookie,如果cookie不过期,则一直有效
    builder.cookieJar(new CookieJarImpl(new DBCookieStore(this)));              //使用数据库保持cookie,如果cookie不过期,则一直有效
    //builder.cookieJar(new CookieJarImpl(new MemoryCookieStore()));            //使用内存保持cookie,app退出后,cookie消失

    //https相关设置,以下几种方案根据需要自己设置
    //方法一:信任所有证书,不安全有风险
    HttpsUtils.SSLParams sslParams1 = HttpsUtils.getSslSocketFactory();
    //方法二:自定义信任规则,校验服务端证书
    HttpsUtils.SSLParams sslParams2 = HttpsUtils.getSslSocketFactory(new SafeTrustManager());
    //方法三:使用预埋证书,校验服务端证书(自签名证书)
    //HttpsUtils.SSLParams sslParams3 = HttpsUtils.getSslSocketFactory(getAssets().open("srca.cer"));
    //方法四:使用bks证书和密码管理客户端证书(双向认证),使用预埋证书,校验服务端证书(自签名证书)
    //HttpsUtils.SSLParams sslParams4 = HttpsUtils.getSslSocketFactory(getAssets().open("xxx.bks"), "123456", getAssets().open("yyy.cer"));
    builder.sslSocketFactory(sslParams1.sSLSocketFactory, sslParams1.trustManager);
    //配置https的域名匹配规则,详细看demo的初始化介绍,不需要就不要加入,使用不当会导致https握手失败
    builder.hostnameVerifier(new SafeHostnameVerifier());

    // 其他统一的配置
    // 详细说明看GitHub文档:https://github.com/jeasonlzy/
    OkGo.getInstance().init(this)                           //必须调用初始化
            .setOkHttpClient(builder.build())               //建议设置OkHttpClient,不设置会使用默认的
            .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式,默认不使用缓存,可以不传
            .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间,默认永不过期,可以不传
            .setRetryCount(3)                               //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
            .addCommonHeaders(headers)                      //全局公共头
            .addCommonParams(params);                       //全局公共参数
}
 
Example #24
Source File: RxCacheActivity.java    From okhttp-OkGo with Apache License 2.0 4 votes vote down vote up
@OnClick(R.id.cache)
public void cache(View view) {

    // 详细看文档: https://github.com/jeasonlzy/okhttp-OkGo/wiki/OkRx

    OkGo.<String>post(Urls.URL_METHOD)//
            .headers("aaa", "111")//
            .params("bbb", "222")//
            .cacheKey("rx_cache")              //这里完全同okgo的配置一样
            .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)  //这里完全同okgo的配置一样
            .converter(new StringConvert())//
            .adapt(new ObservableResponse<String>())//
            .subscribeOn(Schedulers.io())//
            .doOnSubscribe(new Consumer<Disposable>() {
                @Override
                public void accept(@NonNull Disposable disposable) throws Exception {
                    showLoading();
                }
            })//
            .observeOn(AndroidSchedulers.mainThread())//
            .subscribe(new Observer<Response<String>>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {
                    addDisposable(d);
                }

                @Override
                public void onNext(@NonNull Response<String> response) {
                    handleResponse(response);
                }

                @Override
                public void onError(@NonNull Throwable e) {
                    e.printStackTrace();
                    showToast("请求失败");
                    handleError(null);
                }

                @Override
                public void onComplete() {
                    dismissLoading();
                }
            });
}
 
Example #25
Source File: MyApplication.java    From PocketEOS-Android with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void initOkGo() throws IOException {
        HttpHeaders  headers  = new HttpHeaders();
        if (new SPCookieStore(this).getAllCookie().size() != 0) {
            headers.put("Set-Cookie", String.valueOf(mSPCookieStore.getCookie(HttpUrl.parse(BaseUrl.HTTP_Get_code_auth))));
        }
        headers.put("version", "3.0");
        if (Utils.getSpUtils().getString("loginmode", "").equals("phone")) {
            headers.put("uid", MyApplication.getDaoInstant().getUserBeanDao().queryBuilder().where(UserBeanDao.Properties.Wallet_phone.eq(Utils.getSpUtils().getString("firstUser"))).build().unique().getWallet_uid());
        } else {
            headers.put("uid", "6f1a8e0eb24afb7ddc829f96f9f74e9d");
        }


        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        //log相关
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor("OkHttp");
        loggingInterceptor.setPrintLevel(HttpLoggingInterceptor.Level.BODY);        //log打印级别,决定了log显示的详细程度
        loggingInterceptor.setColorLevel(Level.INFO);                               //log颜色级别,决定了log在控制台显示的颜色
        builder.addInterceptor(loggingInterceptor);                                 //添加OkGo默认debug日志
        //超时时间设置
        builder.readTimeout(10000, TimeUnit.MILLISECONDS);      //全局的读取超时时间
        builder.writeTimeout(10000, TimeUnit.MILLISECONDS);     //全局的写入超时时间
        builder.connectTimeout(10000, TimeUnit.MILLISECONDS);   //全局的连接超时时间
        builder.cookieJar(new CookieJarImpl(mSPCookieStore));            //使用sp保持cookie,如果cookie不过期,则一直有效


        HttpsUtils.SSLParams sslParams = HttpsUtils.getSslSocketFactory(getAssets().open("server.cer"));
        builder.sslSocketFactory(sslParams.sSLSocketFactory, sslParams.trustManager);
//        //配置https的域名匹配规则,使用不当会导致https握手失败
        builder.hostnameVerifier(HttpsUtils.UnSafeHostnameVerifier);

        // 其他统一的配置
        OkGo.getInstance().init(this)                           //必须调用初始化
                .setOkHttpClient(builder.build())               //必须设置OkHttpClient
                .setCacheMode(CacheMode.NO_CACHE)               //全局统一缓存模式,默认不使用缓存,可以不传
                .setCacheTime(CacheEntity.CACHE_NEVER_EXPIRE)   //全局统一缓存时间,默认永不过期,可以不传
                .setRetryCount(3)          //全局统一超时重连次数,默认为三次,那么最差的情况会请求4次(一次原始请求,三次重连请求),不需要可以设置为0
                .addCommonHeaders(headers);              //全局公共头
//                .addCommonParams(httpParams);                       //全局公共参数

    }
 
Example #26
Source File: HeaderParser.java    From okhttp-OkGo with Apache License 2.0 3 votes vote down vote up
/**
 * 对每个请求添加默认的请求头,如果有缓存,并返回缓存实体对象
 * Cache-Control: max-age=0                            以秒为单位
 * If-Modified-Since: Mon, 19 Nov 2012 08:38:01 GMT    缓存文件的最后修改时间。
 * If-None-Match: "0693f67a67cc1:0"                    缓存文件的ETag值
 * Cache-Control: no-cache                             不使用缓存
 * Pragma: no-cache                                    不使用缓存
 * Accept-Language: zh-CN,zh;q=0.8                     支持的语言
 * User-Agent:                                         用户代理,它的信息包括硬件平台、系统软件、应用软件和用户个人偏好
 * Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
 *
 * @param request     请求类
 * @param cacheEntity 缓存实体类
 * @param cacheMode   缓存模式
 */
public static <T> void addCacheHeaders(Request request, CacheEntity<T> cacheEntity, CacheMode cacheMode) {
    //1. 按照标准的 http 协议,添加304相关请求头
    if (cacheEntity != null && cacheMode == CacheMode.DEFAULT) {
        HttpHeaders responseHeaders = cacheEntity.getResponseHeaders();
        if (responseHeaders != null) {
            String eTag = responseHeaders.get(HttpHeaders.HEAD_KEY_E_TAG);
            if (eTag != null) request.headers(HttpHeaders.HEAD_KEY_IF_NONE_MATCH, eTag);
            long lastModified = HttpHeaders.getLastModified(responseHeaders.get(HttpHeaders.HEAD_KEY_LAST_MODIFIED));
            if (lastModified > 0) request.headers(HttpHeaders.HEAD_KEY_IF_MODIFIED_SINCE, HttpHeaders.formatMillisToGMT(lastModified));
        }
    }
}
 
Example #27
Source File: HeaderParser.java    From BaseProject with Apache License 2.0 3 votes vote down vote up
/**
 * 对每个请求添加默认的请求头,如果有缓存,并返回缓存实体对象
 * Cache-Control: max-age=0                            以秒为单位
 * If-Modified-Since: Mon, 19 Nov 2012 08:38:01 GMT    缓存文件的最后修改时间。
 * If-None-Match: "0693f67a67cc1:0"                    缓存文件的ETag值
 * Cache-Control: no-cache                             不使用缓存
 * Pragma: no-cache                                    不使用缓存
 * Accept-Language: zh-CN,zh;q=0.8                     支持的语言
 * User-Agent:                                         用户代理,它的信息包括硬件平台、系统软件、应用软件和用户个人偏好
 * Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36
 *
 * @param request     请求类
 * @param cacheEntity 缓存实体类
 * @param cacheMode   缓存模式
 */
public static <T> void addCacheHeaders(Request request, CacheEntity<T> cacheEntity, CacheMode cacheMode) {
    //1. 按照标准的 http 协议,添加304相关请求头
    if (cacheEntity != null && cacheMode == CacheMode.DEFAULT) {
        HttpHeaders responseHeaders = cacheEntity.getResponseHeaders();
        if (responseHeaders != null) {
            String eTag = responseHeaders.get(HttpHeaders.HEAD_KEY_E_TAG);
            if (eTag != null) request.headers(HttpHeaders.HEAD_KEY_IF_NONE_MATCH, eTag);
            long lastModified = HttpHeaders.getLastModified(responseHeaders.get(HttpHeaders.HEAD_KEY_LAST_MODIFIED));
            if (lastModified > 0) request.headers(HttpHeaders.HEAD_KEY_IF_MODIFIED_SINCE, HttpHeaders.formatMillisToGMT(lastModified));
        }
    }
}