Retrofit封装
版权声明:本文为博主原创文章,未经博主允许不得转载。
RetrofitManager是封装的一个工具类,在项目中如果频繁使用Retrofit请求数据,使用RetrofitManager可以减少很多代码量
导入一些依赖
- compile 'io.reactivex:rxjava:1.0.14'
- compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
- compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
- compile 'com.squareup.okhttp3:okhttp:3.9.0'
- compile 'com.android.support:recyclerview-v7:26.0.0-alpha1'
- compile 'com.squareup.okio:okio:1.13.0'
- compile 'io.reactivex:rxandroid:1.0.1'
封装的代码如下
- public class RetrofitManager {
- private Retrofit mRetrofit;
- private String baseUrl;
- OkHttpClient client;
- private static RetrofitManager mRetrofitManager;
-
- private RetrofitManager(String baseUrl,OkHttpClient client){
- this.baseUrl=baseUrl;
- this.client=client;
- initRetrofit();
- }
- public static synchronized RetrofitManager getInstance(String baseUrl,OkHttpClient client){
- if (mRetrofitManager == null){
- mRetrofitManager = new RetrofitManager(baseUrl,client);
- }
- return mRetrofitManager;
- }
- private void initRetrofit() {
- mRetrofit = new Retrofit.Builder()
- .baseUrl(baseUrl)
- .addConverterFactory(GsonConverterFactory.create())
- .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
- .client(client)
- .build();
- }
- public <T> T setCreate(Class<T> reqServer){
- return mRetrofit.create(reqServer);
- }
- }
retrofit请求网络的方式是使用注解来发送请求,所以这里还封装了一个Constant,它的作用就是当你
的接口比较多的时候,修改比较方便,
- public class Constant {
- public static final String BASE_URL="http://tingapi.ting.baidu.com/";
- }
使用方法