Android(安卓)Retrofit 笔记之一使用拦截器设置缓存
16lz
2022-05-28
一,定义拦截器
public class Getretrofit { private static OkHttpClient httpclient; private static Retrofit retrofit; public static Retrofit initretrofit(String baseurl) { //缓存路径和大小 File httpcache = new File(Environment.getExternalStorageDirectory(), "httpcache"); int cachesize = 10 * 1024 * 1024; Cache cache = new Cache(httpcache, cachesize); //日志拦截器 HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); //拦截器 Interceptor rewrite_cache_control_interceptor = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request request = chain.request(); LogUtils.d(request.url()); LogUtils.d(request.method()); Response response = chain.proceed(request); LogUtils.d(response.message()); if (NetworkUtil.isNetworkConnected(UIUtils.getContext())) { int maxage = 3;//缓存失效时间,单位为秒 return response.newBuilder() .removeHeader("pragma")//清除头信息,因为服务器如果不支持,会返回一些干扰信息,不清除下面无法生效 .header("cache-control", "public ,max-age=" + maxage) .build(); } return response; } }; httpclient = new OkHttpClient.Builder() .connectTimeout(8, TimeUnit.SECONDS)//设置连接超时 .readTimeout(8, TimeUnit.SECONDS)//读取超时 .writeTimeout(8, TimeUnit.SECONDS)//写入超时 .addInterceptor(logging)//添加日志拦截器 .cache(cache)//把缓存添加进来 .addNetworkInterceptor(rewrite_cache_control_interceptor)//添加缓存拦截器 .build(); retrofit = new Retrofit.Builder() .baseUrl(baseurl) .client(httpclient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create())// RxJava 适配器 .addConverterFactory(GsonConverterFactory.create()) .build(); return retrofit; }}
二,定义网络接口
public interface APIService { @GET("{category}/{count}/{page}") Observable getAndroidInfos(@Path("category") String category, @Path("count") String count, @Path("page") String page); @GET("weather_mini") Observable getNewsInfos(@Query("citykey") String city);}
三,定义返回的bean
public class InfoBean { /** * data : {"yesterday":{"date":"7日星期日","high":"高温 2℃","fx":"西风","low":"低温 -4℃","fl":"","type":"阴"},"city":"北京","aqi":"76","forecast":[{"date":"8日星期一","high":"高温 2℃","fengli":"","low":"低温 -6℃","fengxiang":"西北风","type":"晴"},{"date":"9日星期二","high":"高温 1℃","fengli":"","low":"低温 -7℃","fengxiang":"西北风","type":"晴"},{"date":"10日星期三","high":"高温 -1℃","fengli":"","low":"低温 -10℃","fengxiang":"西北风","type":"晴"},{"date":"11日星期四","high":"高温 -2℃","fengli":"","low":"低温 -10℃","fengxiang":"西南风","type":"晴"},{"date":"12日星期五","high":"高温 1℃","fengli":"","low":"低温 -9℃","fengxiang":"西南风","type":"晴"}],"ganmao":"各项气象条件适宜,无明显降温过程,发生感冒机率较低。","wendu":"-1"} * status : 1000 * desc : OK */ private DataBean data; private int status; private String desc; public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public static class DataBean { /** * yesterday : {"date":"7日星期日","high":"高温 2℃","fx":"西风","low":"低温 -4℃","fl":"","type":"阴"} * city : 北京 * aqi : 76 * forecast : [{"date":"8日星期一","high":"高温 2℃","fengli":"","low":"低温 -6℃","fengxiang":"西北风","type":"晴"},{"date":"9日星期二","high":"高温 1℃","fengli":"","low":"低温 -7℃","fengxiang":"西北风","type":"晴"},{"date":"10日星期三","high":"高温 -1℃","fengli":"","low":"低温 -10℃","fengxiang":"西北风","type":"晴"},{"date":"11日星期四","high":"高温 -2℃","fengli":"","low":"低温 -10℃","fengxiang":"西南风","type":"晴"},{"date":"12日星期五","high":"高温 1℃","fengli":"","low":"低温 -9℃","fengxiang":"西南风","type":"晴"}] * ganmao : 各项气象条件适宜,无明显降温过程,发生感冒机率较低。 * wendu : -1 */ private YesterdayBean yesterday; private String city; private String aqi; private String ganmao; private String wendu; private List forecast; public YesterdayBean getYesterday() { return yesterday; } public void setYesterday(YesterdayBean yesterday) { this.yesterday = yesterday; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getAqi() { return aqi; } public void setAqi(String aqi) { this.aqi = aqi; } public String getGanmao() { return ganmao; } public void setGanmao(String ganmao) { this.ganmao = ganmao; } public String getWendu() { return wendu; } public void setWendu(String wendu) { this.wendu = wendu; } public List getForecast() { return forecast; } public void setForecast(List forecast) { this.forecast = forecast; } public static class YesterdayBean { /** * date : 7日星期日 * high : 高温 2℃ * fx : 西风 * low : 低温 -4℃ * fl : * type : 阴 */ private String date; private String high; private String fx; private String low; private String fl; private String type; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getHigh() { return high; } public void setHigh(String high) { this.high = high; } public String getFx() { return fx; } public void setFx(String fx) { this.fx = fx; } public String getLow() { return low; } public void setLow(String low) { this.low = low; } public String getFl() { return fl; } public void setFl(String fl) { this.fl = fl; } public String getType() { return type; } public void setType(String type) { this.type = type; } } public static class ForecastBean { /** * date : 8日星期一 * high : 高温 2℃ * fengli : * low : 低温 -6℃ * fengxiang : 西北风 * type : 晴 */ private String date; private String high; private String fengli; private String low; private String fengxiang; private String type; public String getDate() { return date; } public void setDate(String date) { this.date = date; } public String getHigh() { return high; } public void setHigh(String high) { this.high = high; } public String getFengli() { return fengli; } public void setFengli(String fengli) { this.fengli = fengli; } public String getLow() { return low; } public void setLow(String low) { this.low = low; } public String getFengxiang() { return fengxiang; } public void setFengxiang(String fengxiang) { this.fengxiang = fengxiang; } public String getType() { return type; } public void setType(String type) { this.type = type; } } }}
四,使用
Retrofit retrofit = Getretrofit.initretrofit(baseurl); APIService service = retrofit.create(APIService.class); service.getNewsInfos("101010100") .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer() { @Override public void onSubscribe(Disposable d) { d.dispose(); } @Override public void onNext(InfoBean infoBean) { //LogUtils.object(infoBean); LogUtils.d(infoBean); } @Override public void onError(Throwable e) { LogUtils.d(e.getMessage()); } @Override public void onComplete() { } });