Retrofit网络框架的封装使用

retrofit的使用实例(封装以后比较简单明了)

     //联网登录请求的使用
        Map<String, String> map = new HashMap<>();
        map.put("userName" , phone);
        map.put("passWord" , pwd);

        System.out.println(phone + "----" + pwd);
        UseCase addressNetUpdate = new LoginUpdate(map);
        addressNetUpdate.execute(new ResponseSubscriber<UpdateNetBean>() {
            @Override
            public void onFailure(Throwable e) {

                e.printStackTrace();
                loginView.loginError("服务器繁忙,请稍后重试");
            }

            @Override
            public void onSuccess(UpdateNetBean updateNetBean) {

                int infoCode = updateNetBean.getInfoCode();
                if (infoCode == 200){
                    loginView.loginSuccess(phone);
                }else{
                    loginView.loginError("商户号或密码错误");
                }

            }
        });
  • LoginUpdate类的使用
/**
 * Created by shiqiang on 2017/2/23.
 */
public class LoginUpdate extends UseCase {
    public Map<String, String> map;

    public LoginUpdate(Map<String,String> map){
        super();
        this.map = map;
    }

//Rxjava中的被观察者:Observable 
    @Override
    protected Observable buildUseCaseObservable() {
        return RetrofitServiceFactory.getAppService().updateNetCall(map);
    }
}
  • 上面返回的Observable 在何时被调用.execute()的时候封装了,代码如下
public abstract class UseCase {
    private final ThreadExecutor threadExecutor;
    private final PostExecutionThread postExecutionThread;

    private Subscription subscription = Subscriptions.empty();

    protected UseCase() {

        //分别对应线程池跟主线程,下面贴出代码
        this.threadExecutor = JobExecutor.getInstance();
        this.postExecutionThread = UIThread.getInstance();
    }

    //调取时候的代码,使用Rxjava订阅者模式
    public void execute(Subscriber UseCaseSubscriber) {

        this.subscription = this.buildUseCaseObservable()//调取子类
                .subscribeOn(Schedulers.from(threadExecutor))//网络请求在子线程中,创建的线程池,代码下面贴在下面
                .observeOn(postExecutionThread.getScheduler())//返回的结果在主线程中回调给view做数据的处理,使用单例模式封装主线程UI进程
                .subscribe(UseCaseSubscriber);
    }

    public void unSubscribe() {
        if (!subscription.isUnsubscribed()) {
            subscription.unsubscribe();
        }
    }

    protected abstract Observable buildUseCaseObservable();

}

  • 创建buildUseCaseObservable的原理为:
  @Override
    protected Observable buildUseCaseObservable() {
        return RetrofitServiceFactory.getAppService().updateNetCall(map);
    }


/**
 * 根据不同功能模块返回不同的Service接口对象
 */
public class RetrofitServiceFactory {

    //网络请求头
    private static final String Base_URL = UserContentURL.URL_SERVER;

    public static NetworkApi getAppService(){
        return AppRetrofit.getNewsRetrofit(NetworkApi.class,Base_URL);
    }

}


public class AppRetrofit {

    public static <T> T getNewsRetrofit(Class<T> clazz, String baseUrl) {

        if (TextUtils.isEmpty(baseUrl)) {
            throw new IllegalArgumentException("BaseUrl cannot be null");
        }
//

        /**
         * 判断是否需要缓存数据,默认为false,可以用单利在每次请求之前设置值
         */
//        if (true){
        if (App.getIsChach()){

            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl) //刚刚添加进来的请求头
                    .client(getCacheOkHttpClient(App.getApplication()))  //使用缓存,Interceptor截获每次网络请求用于缓存数据
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())  //添加Rxjava

                    //添加Gson解析
                    .addConverterFactory(GsonConverterFactory.create())

                    .build();
            return retrofit.create(clazz);
        }else{
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(baseUrl)
                    .client(getOKHttpClient())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    //添加Gson解析
                    .addConverterFactory(GsonConverterFactory.create())

                    .build();
            return retrofit.create(clazz);
        }

    }


//网络请求时间的设置
    private static OkHttpClient getOKHttpClient(){
        return new OkHttpClient.Builder()
//                .connectTimeout(20000, TimeUnit.MILLISECONDS)
                .connectTimeout(10000, TimeUnit.SECONDS)
                .writeTimeout(10000, TimeUnit.SECONDS)
                .readTimeout(10000, TimeUnit.SECONDS)
                .build();
    }

    //缓存的代码
    private static OkHttpClient getCacheOkHttpClient(final Context context){
        final File baseDir = context.getCacheDir();
        final File cacheDir = new File(baseDir, "HttpResponseCache");
//        Timber.e(cacheDir.getAbsolutePath());
        Cache cache = new Cache(cacheDir, 10 * 1024 * 1024);   //缓存可用大小为10M

        //Retrofit网络请求时候的截获类Interceptor
        Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                            Request request = chain.request();
            if(!NetWorkUtils.isNetWorkAvailable(context)){
                request = request.newBuilder()
                        .cacheControl(CacheControl.FORCE_CACHE)
                        .build();
            }

            Response originalResponse = chain.proceed(request);
            if (NetWorkUtils.isNetWorkAvailable(context)) {
                int maxAge = 60;                  //在线缓存一分钟
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, max-age=" + maxAge)
                        .build();

            } else {
                int maxStale = 60 * 60 * 24 * 4 * 7;     //离线缓存4周
                return originalResponse.newBuilder()
                        .removeHeader("Pragma")
                        .removeHeader("Cache-Control")
                        .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)

                        .build();
            }


            }
        };


        return new OkHttpClient.Builder()
                .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR)
                .cache(cache)
                .connectTimeout(10000, TimeUnit.SECONDS)
                .writeTimeout(10000, TimeUnit.SECONDS)
                .readTimeout(10000, TimeUnit.SECONDS)
                .build();
    }


}

  • 观察者,请求以后的回调,由于 ResponseSubscriber extends Subscriber ,儿Subscriber
//使用了Gson可以直接转化对象
addressNetUpdate.execute(new ResponseSubscriber<UpdateNetBean>() {
            @Override
            public void onFailure(Throwable e) {

                e.printStackTrace();
                loginView.loginError("服务器繁忙,请稍后重试");
            }

            @Override
            public void onSuccess(UpdateNetBean updateNetBean) {

                int infoCode = updateNetBean.getInfoCode();
                if (infoCode == 200){
                    loginView.loginSuccess(phone);
                }else{
                    loginView.loginError("商户号或密码错误");
                }

            }
        });

[源码github地址](“https://github.com/weiaiCmeng/RetrofitTest“)

猜你喜欢

转载自blog.csdn.net/wei_ai_n/article/details/62046208