首先需要添加一些依赖
compile 'io.reactivex:rxandroid:1.2.0'
compile 'io.reactivex:rxjava:1.1.5'
compile 'com.google.code.gson:gson:2.4'
compile 'com.squareup.retrofit2:retrofit:2.0.2'
compile 'com.squareup.retrofit2:converter-gson:2.0.2'
compile 'com.squareup.retrofit2:converter-jackson:2.0.0'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
compile 'com.squareup.okhttp3:okhttp:3.0.1'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'
compile 'com.squareup.okio:okio:1.6.0'
然后自定义封装一个网络访问的类
public class NetManager {
private NetService mNetService;
/**
* 设缓存有效期为两天
*/
private static final long CACHE_STALE_SEC = 60 * 60 * 24 * 2;
/**
* 查询缓存的Cache-Control设置,为if-only-cache时只查询缓存而不会请求服务器,max-stale可以配合设置缓存失效时间
* max-stale 指示客户机可以接收超出超时期间的响应消息。如果指定max-stale消息的值,那么客户机可接收超出超时期指定值之内的响应消息。
*/
private static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;
/**
* 查询网络的Cache-Control设置,头部Cache-Control设为max-age=0
* (假如请求了服务器并在a时刻返回响应结果,则在max-age规定的秒数内,浏览器将不会发送对应的请求到服务器,数据由缓存直接返回)时则不会使用缓存而请求服务器
*/
private static final String CACHE_CONTROL_AGE = "max-age=0";
private static volatile OkHttpClient sOkHttpClient;
private static SparseArray<NetManager> sRetrofitManager = new SparseArray<>(HostType.TYPE_COUNT);
public NetManager(int hostType){
Retrofit retrofit = new Retrofit.Builder().baseUrl(URLConstants.getHost(hostType))
.client(getOkHttpClient()).addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();
mNetService=retrofit.create(NetService.class);//生成不同的service
}
private OkHttpClient getOkHttpClient() {
if (sOkHttpClient == null) {
synchronized (NetManager.class) {
Cache cache = new Cache(new File(App.getAppContext().getCacheDir(), "HttpCache"),
1024 * 1024 * 100);
if (sOkHttpClient == null) {
sOkHttpClient = new OkHttpClient.Builder().cache(cache)
.connectTimeout(6, TimeUnit.SECONDS)
.readTimeout(6, TimeUnit.SECONDS)
.writeTimeout(6, TimeUnit.SECONDS)
.addInterceptor(mRewriteCacheControlInterceptor)
.addNetworkInterceptor(mRewriteCacheControlInterceptor)
.addInterceptor(mLoggingInterceptor).build();
}
}
}
return sOkHttpClient;
}
/**
* 云端响应头拦截器,用来配置缓存策略
* Dangerous interceptor that rewrites the server's cache-control header.
*/
private final Interceptor mRewriteCacheControlInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
if (!NetUtil.isNetworkAvailable()) {
request = request.newBuilder()
.cacheControl(CacheControl.FORCE_CACHE)
.build();
Log.d("net","no network");
}
Response originalResponse = chain.proceed(request);
if (NetUtil.isNetworkAvailable()) {
//有网的时候读接口上的@Headers里的配置,你可以在这里进行统一的设置
String cacheControl = request.cacheControl().toString();
return originalResponse.newBuilder()
.header("Cache-Control", cacheControl)
.removeHeader("Pragma")
.build();
} else {
return originalResponse.newBuilder()
.header("Cache-Control", "public, only-if-cached, max-stale=" + CACHE_STALE_SEC)
.removeHeader("Pragma")
.build();
}
}
};
private final Interceptor mLoggingInterceptor = new Interceptor() {
@Override
public Response intercept(Chain chain) throws IOException {
Request request = chain.request();
Log.e("net",request.url()+"");
long t1 = System.nanoTime();
Log.i("net",String.format("Sending request %s on %s%n%s", request.url(), chain.connection(), request.headers()));
Response response = chain.proceed(request);
long t2 = System.nanoTime();
Log.i("net",String.format(Locale.getDefault(), "Received response for %s in %.1fms%n%s",
response.request().url(), (t2 - t1) / 1e6d, response.headers()));
return response;
}
};
/**
* @param hostType NETEASE_NEWS_VIDEO:1 (新闻,视频),GANK_GIRL_PHOTO:2(图片新闻);
* EWS_DETAIL_HTML_PHOTO:3新闻详情html图片)
* 获取不同的Service
*/
public static NetService getDefault(int hostType)
{
NetManager netManager = sRetrofitManager.get(hostType);
if (netManager == null)
{
netManager = new NetManager(hostType);
sRetrofitManager.put(hostType, netManager);
}
return netManager.mNetService;
}
/**
* 根据网络状况获取缓存的策略
*/
@NonNull
private String getCacheControl() {
return NetUtil.isNetworkAvailable() ? CACHE_CONTROL_AGE : CACHE_CONTROL_CACHE;
}
}
定义一个接口的样式
public interface NetService {
/**
* 加载图片地址
*/
@GET("data/福利/{pageCount}/{page}")
Observable<PhotoEntity> getPhotoList(@Path("pageCount") int pageCount, @Path("page") int page);
}
最后进行网络访问
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Observable<PhotoEntity> observable= NetManager.getDefault(HostType.GANK_GIRL_PHOTO).getPhotoList(10, 1).compose(TransformUtils.<PhotoEntity>defaultSchedulers());
observable.subscribe(new NetBaseSubscriber<PhotoEntity>(getApplicationContext()) {
@Override
public void onStart() {
super.onStart();
}
@Override
public void onCompleted() {
super.onCompleted();
}
@Override
public void onError(Throwable e) {
super.onError(e);
}
@Override
public void onNext(PhotoEntity photoEntity) {
super.onNext(photoEntity);
textView.setText(photoEntity.toString());
}
});
}
});