一、集成方式(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; } }