安卓RXJAVA+Retrofit 网络请求


先贴AddressMangager使用方式

AddressMangager使用方式

gradle加入

//Retrofit 网络请求

compile 'com.squareup.retrofit2:retrofit:2.3.0'

compile 'com.squareup.retrofit2:converter-gson:2.3.0'

//RXJAVA

compile 'io.reactivex:rxjava:1.3.0'

compile 'io.reactivex:rxandroid:1.2.1'

compile 'com.squareup.retrofit2:adapter-rxjava:2.3.0'

工具类 需修改URL_LOCATION头

public class HttpUtils {

private static final String URL_LOCATION = AddressManager.getHost();

private static final int NET_MAX = 30; //30秒 有网超时时间

private static final int NO_NET_MAX = 60 * 60 * 24 * 7; //7天 无网超时时间

public static Retrofit getRetrofit(String url, final Context context) {

//应用程序拦截器

Interceptor mInterceptor = new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

//Log.e("TAG", "拦截 网络 缓存");

Request request = chain.request();

if (!NetWorkUtils.networkIsAvailable(context)) {//判断网络状态 无网络时

//Log.e("TAG", "无网~~ 缓存");

request = request.newBuilder()

//Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache-Control:no-cache相同。为了确保缓存生效

.removeHeader("Pragma")

.header("Cache-Control", "private, only-if-cached, max-stale=" + NO_NET_MAX)

.build();

} else {//有网状态

//Log.e("TAG", "有网~~ 缓存");

request = request.newBuilder()

//Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache-Control:no-cache相同。为了确保缓存生效

.removeHeader("Pragma")

.header("Cache-Control", "private, max-age=" + NET_MAX)//添加缓存请求头

.build();

}

return chain.proceed(request);

}

};

//网络拦截器

Interceptor mNetInterceptor = new Interceptor() {

@Override

public Response intercept(Chain chain) throws IOException {

//Log.e("TAG", "拦截 应用 缓存");

Request request = chain.request();

if (!NetWorkUtils.networkIsAvailable(context)) {//判断网络状态 无网络时

request = request.newBuilder()

//Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache-Control:no-cache相同。为了确保缓存生效

.removeHeader("Pragma")

.header("Cache-Control", "private, only-if-cached, max-stale=" + NO_NET_MAX)

.build();

} else {

request = request.newBuilder()

//Pragma:no-cache。在HTTP/1.1协议中,它的含义和Cache-Control:no-cache相同。为了确保缓存生效

.removeHeader("Pragma")

.header("Cache-Control", "private, max-age=" + NET_MAX)//添加缓存请求头

.build();

}

Response response = chain.proceed(request);

ResponseBody responseBody = response.peekBody(1024 * 1024);

Log.d("zhengwu", responseBody.string());

return response;

}

};

File mFile = new File(context.getCacheDir() + "http");//储存目录

long maxSize = 10 * 1024 * 1024; // 10 MB 最大缓存数

Cache mCache = new Cache(mFile, maxSize);

OkHttpClient mClient = new OkHttpClient.Builder()

.addInterceptor(mInterceptor)//应用程序拦截器

.addNetworkInterceptor(mNetInterceptor)//网络拦截器

.cache(mCache)//添加缓存

.build();

Retrofit retrofit = new Retrofit.Builder()

.baseUrl(url)

.client(mClient)//添加OK

.addConverterFactory(GsonConverterFactory.create())

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

.build();

return retrofit;

}

public static iHttpService createService(Context context) {

return getRetrofit(URL_LOCATION, context).create(iHttpService.class);

}

}

文中涉及到文件NetWorkUtils

public class NetWorkUtils {

public static String type = "";

public static String getCurrentNetType(Context context) {

ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo info = cm.getActiveNetworkInfo();

if (info == null) {

type = "null";

} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {

type = "wifi";

} else if (info.getType() == ConnectivityManager.TYPE_MOBILE) {

int subType = info.getSubtype();

if (subType == TelephonyManager.NETWORK_TYPE_CDMA

|| subType == TelephonyManager.NETWORK_TYPE_GPRS

|| subType == TelephonyManager.NETWORK_TYPE_EDGE) {

type = "2g";

} else if (subType == TelephonyManager.NETWORK_TYPE_UMTS

|| subType == TelephonyManager.NETWORK_TYPE_HSDPA

|| subType == TelephonyManager.NETWORK_TYPE_EVDO_A

|| subType == TelephonyManager.NETWORK_TYPE_EVDO_0

|| subType == TelephonyManager.NETWORK_TYPE_EVDO_B) {

type = "3g";

} else if (subType == TelephonyManager.NETWORK_TYPE_LTE) {// LTE是3g到4g的过渡,是3.9G的全球标准

type = "4g";

}

}

return type;

}

public static boolean networkIsAvailable(Context context) {

if (getCurrentNetType(context).equals("null")) {

return false;

} else {

return true;

}

}

}

加入一个interface接口文件,取名iHttpService

举例:

@GET("intertidwebapp/ws/api/letter/getChanList")

Observable<ChanListModel> getChanList(@Query("PageIndex") int PageIndex, //(名称:当前页;类型:int;必填)

@Query("PageSize") int PageSize, //(名称:每页条数;类型:int;必填,默认填20)

@Query("ChanID") int ChanID, //(名称:频道号;类型:int;必填,固定值;测试无锡要闻-11084,测试公示公告-11099,市委书记李小敏-13999,市长汪泉-14001)

@Query("SiteID") int SiteID, //(名称:站点ID;类型:int;必填,固定值,125)

@Query("IsImg") int IsImg //(名称:是否返回图片路径;类型:int,非必填,固定值,1)

);

activity引用举例

首先声明service

private iHttpService service;

初始化service

service = HttpUtils.createService(getActivity());

private void initnewsData() {

service.getChanList(page, 20, 11084, 125, 1)

.subscribeOn(Schedulers.io())//指定网络请求在IO线程

.doOnSubscribe(new Action0() {

@Override

public void call() {

DialogLoading.StartLodingDialog(getActivity());

}

})

.subscribeOn(AndroidSchedulers.mainThread())//显示Dialog在主线程中

.observeOn(AndroidSchedulers.mainThread())//显示数据在主线程

.subscribe(new Subscriber<ChanListModel>() {

@Override

public void onCompleted() {

DialogLoading.StopLodingDialog();

}

@Override

public void onError(Throwable e) {

DialogLoading.StopLodingDialog();

Util.toastMsg("网络连接失败");

}

@Override

public void onNext(ChanListModel backchanListModel) {

newschanListModel = backchanListModel;

}

});

}