Retrofit封装

来源:互联网 发布:机械制图软件视频教程 编辑:程序博客网 时间:2024/05/21 17:34


    Retrofit封装

 
标签: android
43人阅读 评论(0)收藏举报

RetrofitManager是封装的一个工具类,在项目中如果频繁使用Retrofit请求数据,使用RetrofitManager可以减少很多代码量

导入一些依赖

 

  1.  compile 'io.reactivex:rxjava:1.0.14'  
  2.    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'  
  3.    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'  
  4.    compile 'com.squareup.okhttp3:okhttp:3.9.0'  
  5.    compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'  
  6.    compile 'com.squareup.okio:okio:1.13.0'  
  7.    compile 'io.reactivex:rxandroid:1.0.1' 


封装的代码如下

[html] view plain copy
  1. public class RetrofitManager {  
  2.     private Retrofit mRetrofit;  
  3.     private String baseUrl;  
  4.     OkHttpClient client;  
  5.     private static RetrofitManager mRetrofitManager;  
  6.    
  7.     private RetrofitManager(String baseUrl,OkHttpClient client){  
  8.         this.baseUrl=baseUrl;  
  9.         this.client=client;  
  10.         initRetrofit();  
  11.     }  
  12.     public static synchronized RetrofitManager getInstance(String baseUrl,OkHttpClient client){  
  13.         if (mRetrofitManager == null){  
  14.             mRetrofitManager = new RetrofitManager(baseUrl,client);  
  15.         }  
  16.         return mRetrofitManager;  
  17.     }  
  18.   
  19.     private void initRetrofit() {  
  20.         mRetrofit = new Retrofit.Builder()  
  21.                 .baseUrl(baseUrl)  
  22.                 .addConverterFactory(GsonConverterFactory.create())  
  23.                 .addCallAdapterFactory(RxJavaCallAdapterFactory.create())  
  24.                 .client(client)  
  25.                 .build();  
  26.     }  
  27.     public <T> T setCreate(Class<T> reqServer){  
  28.         return mRetrofit.create(reqServer);  
  29.     }  
  30. }  

retrofit请求网络的方式是使用注解来发送请求,所以这里还封装了一个Constant,它的作用就是当你

的接口比较多的时候,修改比较方便,

[html] view plain copy
                     域名的类
  1. public class Constant {  
  2.     public static final String BASE_URL="http://tingapi.ting.baidu.com/";  
  3. }  

使用方法
[html] view plain copy

  1.  OkHttpClient okclient = new OkHttpClient.Builder().build();
  2. RetrofitManager.getInstance(Constant.BASE_URL,client) //Constant域名的类
  3.                 .setCreate(MusicService.class)  //MusicService是注解的类
  4.                 .getshu()  
  5.                 .observeOn(AndroidSchedulers.mainThread())  
  6.                 .subscribeOn(Schedulers.io())  
  7.                 .subscribe(observer);