RxJava+Retrofit+okhttp实践结合
来源:互联网 发布:方正兰亭纤黑简体 mac 编辑:程序博客网 时间:2024/06/05 09:01
1.强强联合
RxJava + Retrofit + okhttp
2.build.gradle文件中添加如下内容
compile 'com.android.support:appcompat-v7:23.4.0'compile 'io.reactivex:rxjava:1.0.10'compile 'io.reactivex:rxandroid:1.2.0'compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'compile 'com.google.code.gson:gson:2.6.2'
3. 创建各种帮助类
3.1 创建缓存帮助类 主要是方便缓存 需要选择好缓存路径和缓存文件大小
public class CacheHelper { private Cache mCache; //设置缓存目录 private static File cacheFile; private static long maxSize = 8*1024*1024; private CacheHelper(){ cacheFile = new File(MyApplication.getContext().getCacheDir().getAbsolutePath(), "mycache"); } private static CacheHelper helper; public static CacheHelper getInstance(){ if(helper==null){ synchronized (CacheHelper.class){ if(helper==null){ helper = new CacheHelper(); } } } return helper; } //返回缓存对象 public Cache getCache(){ if(mCache ==null) mCache = new Cache(cacheFile, maxSize); return mCache; }}
3.2 创建OkHttp帮助类 主要是结合OkHttp 提高请求效率
public class OkHttpClientHelper { private final Cache cache; private OkHttpClient mClient; private final static long TIMEOUT = 10000; //超时时间 private OkHttpClientHelper(){ cache = CacheHelper.getInstance().getCache(); } private static OkHttpClientHelper clientHelper; public static OkHttpClientHelper getInstance(){ if(clientHelper==null){ synchronized (OkHttpClientHelper.class){ if(clientHelper==null){ clientHelper = new OkHttpClientHelper(); } } } return clientHelper; } //获取OKHttpClicent对象 public OkHttpClient getOkHttpClient(){ if(mClient ==null) { mClient = new OkHttpClient.Builder() .connectTimeout(TIMEOUT, TimeUnit.SECONDS) .readTimeout(TIMEOUT, TimeUnit.SECONDS) .writeTimeout(TIMEOUT, TimeUnit.SECONDS) .cache(cache) //设置缓存 .build(); } return mClient; }}
3.3 创建Retrofit帮助类
public class RetrofitHelper { private final OkHttpClient mClient; private Retrofit mRetrofit; private RetrofitHelper(){ mClient = OkHttpClientHelper.getInstance().getOkHttpClient(); } private static RetrofitHelper helper; //单例 保证对象唯一 public static RetrofitHelper getInstance(){ if(helper==null){ synchronized (RetrofitHelper.class){ if(helper==null){ helper = new RetrofitHelper(); } } } return helper; } //获取Retrofit对象 public Retrofit getRetrofit(String url){ if(mRetrofit==null) { mRetrofit = new Retrofit.Builder() .baseUrl(url + "/") .addConverterFactory(GsonConverterFactory.create()) //添加Gson支持 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加RxJava支持 .client(mClient) //关联okhttp .build(); } return mRetrofit; }}
3.4 创建Http工具类 封装各种网络请求方式
public class HttpUtils { private static MavinService mService; //Post方式请求网络 public static void requestNetByPost(String url, String uid,Subscriber subscriber){ setSubscriber(getService(url).getInfoByPost(uid),subscriber); } //Get方式请求网络 public static void requestNetByGet(String url,String uid,Subscriber subscriber){ setSubscriber(getService(url).getInfoByGet(uid),subscriber); } //Post map 方式请求网络 public static void requestNetByPostMap(String url, Map<Integer,String> map,Subscriber subscriber){ setSubscriber(getService(url).getInfoByPostMap(map),subscriber); } //Get map方式请求网络 public static void requestNetByGetMap(String url, Map<Integer,String> map,Subscriber subscriber){ setSubscriber(getService(url).getInfoByGetMap(map),subscriber); } //设置缓存 public static void getCache(String url,String uid,Subscriber subscriber){ setSubscriber(getService(url).getCache(uid),subscriber); } //订阅事件 public static<T> void setSubscriber(Observable<T> observable, Subscriber<T> subscriber){ observable.subscribeOn(Schedulers.newThread()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); } //获取服务对象 private static MavinService getService(String url){ if(mService==null) { mService = RetrofitHelper.getInstance() .getRetrofit(url) .create(MavinService.class); } return mService; }}
4 创建实体类和服务类
4.1 创建实体类 不解释 用于Gson解析
public class MavinInfo { public String ANDROID_VERSION; public String ANDROID_VERSION_CODE; public String IOS_VERSION; public String IOS_VERSION_CODE; public String msg; public String status; public List<BodyBean> body; public static class BodyBean { public String body_img; public String title; public String trueName; public int uid; @Override public String toString() { return "BodyBean{" + "body_img='" + body_img + '\'' + ", title='" + title + '\'' + ", trueName='" + trueName + '\'' + ", uid=" + uid + '}'; } }}
4.2 创建服务类接口 Retrofit请求必须的
public interface MavinService{ String MAVIN = "json/tjMavin.htm"; String FIELD = "uid"; //设缓存有效期为1天 long CACHE_STALE_SEC = 60 * 60 * 24 * 1; //查询缓存的Cache-Control设置,使用缓存 String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC; //查询网络的Cache-Control设置。不使用缓存 String CACHE_CONTROL_NETWORK = "max-age=0"; //Post请求 @FormUrlEncoded @POST(MAVIN) Observable<MavinInfo> getInfoByPost(@Field(FIELD) String uid); //GET请求 @GET(MAVIN) Observable<MavinInfo> getInfoByGet(@Query(FIELD) String uid); //POST map @FormUrlEncoded @POST(MAVIN) Observable<MavinInfo> getInfoByPostMap(@FieldMap Map<Integer,String> map); //GET请求 map @GET(MAVIN) Observable<MavinInfo> getInfoByGetMap(@QueryMap Map<Integer,String> map); //GET请求,设置缓存 @Headers("Cache-Control: public," + CACHE_CONTROL_CACHE) @GET(MAVIN) Observable<MavinInfo> getCache(@Query(FIELD) String uid);}
5 Activity中实现
//Get请求 mBtn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getInfo("GET"); } }); //Post请求 mBtn2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { getInfo("POST"); } }); private void getInfo(String type) { if(type.equals("GET")){ HttpUtils.requestNetByGet(url, "33201", new Subscriber<MavinInfo>() { @Override public void onCompleted() { Log.e("get onCompleted","读取完成"); } @Override public void onError(Throwable e) { Log.e("get onError",e.getMessage()); } @Override public void onNext(MavinInfo info) { if(info.body==null || info.body.size()<=0) return; for (MavinInfo.BodyBean bean : info.body) { Log.e("get onNext ",bean.toString()); } } }); }else{ HttpUtils.requestNetByPost(url, "33201", new Subscriber<MavinInfo>() { @Override public void onCompleted() { Log.e("post onCompleted","读取完成"); } @Override public void onError(Throwable e) { Log.e("post onError",e.getMessage()); } @Override public void onNext(MavinInfo info) { if(info.body==null || info.body.size()<=0) return; for (MavinInfo.BodyBean bean : info.body) { Log.e("post onNext ",bean.toString()); } } }); } }
6 联系方式
QQ:1509815887
邮箱:zlc921022@163.com
源代码下载
2 0
- RxJava+Retrofit+okhttp实践结合
- RxJava RxAndroid Retrofit实践结合
- rxjava+retrofit+okhttp+mvp 简单实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- Retrofit结合RxJava的一次实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- RxJava 与 Retrofit 结合的最佳实践
- eclipse for c++ 快捷键
- open edX在Ubuntu 12.04中的安装
- python win32com模块
- PHP中几种常见的超时处理全面总结(二)
- LeetCode No.410 Split Array Largest Sum
- RxJava+Retrofit+okhttp实践结合
- 最大公因数——解题报告
- 数据结构字符串匹配——KMP算法
- C语言程序之打印菱形星号
- SSM框架---详细整合教程(Spring+SpringMVC+MyBatis)
- E-R图(Entity Relationship Diagram实体联系图)
- VS2015 C++无法加载mspdb140.dll错误解决方法
- 设计模式--组合模式
- HEVC学习(一) —— HM的使用