RxJava + Retrofit + okhttp
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'io.reactivex:rxjava:1.0.10'
compile 'io.reactivex:rxandroid:1.2.0'
compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.retrofit2:adapter-rxjava:2.0.0-beta4'
compile 'com.google.code.gson:gson:2.6.2'
3.1 创建缓存帮助类 主要是方便缓存 需要选择好缓存路径和缓存文件大小
public class CacheHelper {
private Cache mCache;
//设置缓存目录
private static File cacheFile;
private static long maxSize = 8*1024*1024;
private CacheHelper(){
cacheFile = new File(MyApplication.getContext().getCacheDir().getAbsolutePath(), "mycache");
}
private static CacheHelper helper;
public static CacheHelper getInstance(){
if(helper==null){
synchronized (CacheHelper.class){
if(helper==null){
helper = new CacheHelper();
}
}
}
return helper;
}
//返回缓存对象
public Cache getCache(){
if(mCache ==null)
mCache = new Cache(cacheFile, maxSize);
return mCache;
}
}
3.2 创建OkHttp帮助类 主要是结合OkHttp 提高请求效率
public class OkHttpClientHelper {
private final Cache cache;
private OkHttpClient mClient;
private final static long TIMEOUT = 10000; //超时时间
private OkHttpClientHelper(){
cache = CacheHelper.getInstance().getCache();
}
private static OkHttpClientHelper clientHelper;
public static OkHttpClientHelper getInstance(){
if(clientHelper==null){
synchronized (OkHttpClientHelper.class){
if(clientHelper==null){
clientHelper = new OkHttpClientHelper();
}
}
}
return clientHelper;
}
//获取OKHttpClicent对象
public OkHttpClient getOkHttpClient(){
if(mClient ==null) {
mClient = new OkHttpClient.Builder()
.connectTimeout(TIMEOUT, TimeUnit.SECONDS)
.readTimeout(TIMEOUT, TimeUnit.SECONDS)
.writeTimeout(TIMEOUT, TimeUnit.SECONDS)
.cache(cache) //设置缓存
.build();
}
return mClient;
}
}
3.3 创建Retrofit帮助类
public class RetrofitHelper {
private final OkHttpClient mClient;
private Retrofit mRetrofit;
private RetrofitHelper(){
mClient = OkHttpClientHelper.getInstance().getOkHttpClient();
}
private static RetrofitHelper helper;
//单例 保证对象唯一
public static RetrofitHelper getInstance(){
if(helper==null){
synchronized (RetrofitHelper.class){
if(helper==null){
helper = new RetrofitHelper();
}
}
}
return helper;
}
//获取Retrofit对象
public Retrofit getRetrofit(String url){
if(mRetrofit==null) {
mRetrofit = new Retrofit.Builder()
.baseUrl(url + "/")
.addConverterFactory(GsonConverterFactory.create()) //添加Gson支持
.addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //添加RxJava支持
.client(mClient) //关联okhttp
.build();
}
return mRetrofit;
}
}
3.4 创建Http工具类 封装各种网络请求方式
public class HttpUtils {
private static MavinService mService;
//Post方式请求网络
public static void requestNetByPost(String url, String uid,Subscriber subscriber){
setSubscriber(getService(url).getInfoByPost(uid),subscriber);
}
//Get方式请求网络
public static void requestNetByGet(String url,String uid,Subscriber subscriber){
setSubscriber(getService(url).getInfoByGet(uid),subscriber);
}
//Post map 方式请求网络
public static void requestNetByPostMap(String url, Map map,Subscriber subscriber){
setSubscriber(getService(url).getInfoByPostMap(map),subscriber);
}
//Get map方式请求网络
public static void requestNetByGetMap(String url, Map map,Subscriber subscriber){
setSubscriber(getService(url).getInfoByGetMap(map),subscriber);
}
//设置缓存
public static void getCache(String url,String uid,Subscriber subscriber){
setSubscriber(getService(url).getCache(uid),subscriber);
}
//订阅事件
public static void setSubscriber(Observable observable, Subscriber subscriber){
observable.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(subscriber);
}
//获取服务对象
private static MavinService getService(String url){
if(mService==null) {
mService = RetrofitHelper.getInstance()
.getRetrofit(url)
.create(MavinService.class);
}
return mService;
}
}
4.1 创建实体类 不解释 用于Gson解析
public class MavinInfo {
public String ANDROID_VERSION;
public String ANDROID_VERSION_CODE;
public String IOS_VERSION;
public String IOS_VERSION_CODE;
public String msg;
public String status;
public List body;
public static class BodyBean {
public String body_img;
public String title;
public String trueName;
public int uid;
@Override
public String toString() {
return "BodyBean{" +
"body_img='" + body_img + '\'' +
", title='" + title + '\'' +
", trueName='" + trueName + '\'' +
", uid=" + uid +
'}';
}
}
}
4.2 创建服务类接口 Retrofit请求必须的
public interface MavinService{
String MAVIN = "json/tjMavin.htm";
String FIELD = "uid";
//设缓存有效期为1天
long CACHE_STALE_SEC = 60 * 60 * 24 * 1;
//查询缓存的Cache-Control设置,使用缓存
String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;
//查询网络的Cache-Control设置。不使用缓存
String CACHE_CONTROL_NETWORK = "max-age=0";
//Post请求
@FormUrlEncoded
@POST(MAVIN)
Observable getInfoByPost(@Field(FIELD) String uid);
//GET请求
@GET(MAVIN)
Observable getInfoByGet(@Query(FIELD) String uid);
//POST map
@FormUrlEncoded
@POST(MAVIN)
Observable getInfoByPostMap(@FieldMap Map map);
//GET请求 map
@GET(MAVIN)
Observable getInfoByGetMap(@QueryMap Map map);
//GET请求,设置缓存
@Headers("Cache-Control: public," + CACHE_CONTROL_CACHE)
@GET(MAVIN)
Observable getCache(@Query(FIELD) String uid);
}
//Get请求
mBtn1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInfo("GET");
}
});
//Post请求
mBtn2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getInfo("POST");
}
});
private void getInfo(String type) {
if(type.equals("GET")){
HttpUtils.requestNetByGet(url, "33201", new Subscriber() {
@Override
public void onCompleted() {
Log.e("get onCompleted","读取完成");
}
@Override
public void onError(Throwable e) {
Log.e("get onError",e.getMessage());
}
@Override
public void onNext(MavinInfo info) {
if(info.body==null || info.body.size()<=0)
return;
for (MavinInfo.BodyBean bean : info.body) {
Log.e("get onNext ",bean.toString());
}
}
});
}else{
HttpUtils.requestNetByPost(url, "33201", new Subscriber() {
@Override
public void onCompleted() {
Log.e("post onCompleted","读取完成");
}
@Override
public void onError(Throwable e) {
Log.e("post onError",e.getMessage());
}
@Override
public void onNext(MavinInfo info) {
if(info.body==null || info.body.size()<=0)
return;
for (MavinInfo.BodyBean bean : info.body) {
Log.e("post onNext ",bean.toString());
}
}
});
}
}
QQ:1509815887
邮箱:[email protected]