如何封装自己的网络框架(RxJava+okHttp+Retrofit)

一、集成方式(android Studio)

1、添加第三方库的依赖

okhttp

compile 'com.squareup.okhttp3:okhttp:3.5.0'

retrofit

compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'

rxjava

compile 'io.reactivex:rxjava:1.1.6'
compile 'io.reactivex:rxandroid:1.2.1'
2、开始搭建

①创建okhttp的builder

       

OkHttpClient.Builder builder = new OkHttpClient
        .Builder()//创建builder
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)//设置连接服务器的时间
        .addInterceptor(new CommonInterceptor()); //添加拦截器   向请求添加所需参数
	.addInterceptor(new CacheInterceptor());

②CommonInterceptor 的创建  作用:向请求的头 添加必要的信息

public class CommonInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        // 向请求添加参数、形成新的请求
        HttpUrl.Builder newRequest= oldRequest
                .url()
                .newBuilder()
                .addQueryParameter("deviceVersion", android.os.Build.VERSION.RELEASE)
                .addQueryParameter("deviceId", "xxx")
                .scheme(oldRequest.url().scheme())
                .host(oldRequest.url().host())
		.newBuilder()
                .url(authorizedUrlBuilder.build())
                .build();
return chain.proceed(newRequest); }}

③创建Retrofit   

Retrofit retrofit = new Retrofit.Builder()
        .addConverterFactory(GsonConverterFactory.create(new Gson()))
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .client(builder.build())
        .baseUrl(Constants.BASE_URL)
        .build();

④创建Service     请求的就接口

   Service	mService = retrofit.create(Service.class);

⑤创建Service实体类

public interface Service {
	//获取APP的信息 接口    Result 结果的过滤     AppVersionBean  请求的数据Bean

    @GET("app/check_android_version")
    Observable<Result<AppVersionBean>> getAppVersion();
}
  

⑥ CacheIntercepter 缓存

public class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
	//网络状态是否可用
        if (!AppUtils.isNetworkAvailable(BaseApp.application)) {
            // 没网强制时候从缓存读取
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }
	//获取响应体
        Response response = chain.proceed(request);
        Response responseLatest;

        if (AppUtils.isNetworkAvailable(BaseApp.application)) {
            // 有网时候读接口上的@Headers里的配置
            String cacheControl = request.cacheControl().toString();
            responseLatest = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", cacheControl)
                    .build();
        } else {
            int maxStale = 60 * 60 * 24 * 7; //设置失效时间
            responseLatest = response.newBuilder()
                    .removeHeader("Pragma")
                    .removeHeader("Cache-Control")
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .build();
        }
        return responseLatest;
    }
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值