首先导入依赖
Retrofit的依赖
compile 'com.squareup.retrofit2:retrofit:2.0.2'compile 'com.squareup.retrofit2:converter-gson:2.0.2' compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'compile 'com.squareup.okhttp3:okhttp:3.1.2'
compile 'io.reactivex:rxjava:1.0.14' compile 'io.reactivex:rxandroid:1.0.1'
Retrofit+Rxjava+Okhttp框架封装public interface RetroApi {实现RetroApi接口(接口拼接)public static final String BEAN = "http://api.svipmovie.com/"; //首页 @GET("front/homePageApi/homePage.do") Observable<Bean> getBean(); //详情 @GET("front/videoDetailApi/videoDetail.do") Observable<Xiang> getXiang(@Query("mediaId") String mediaId); }实现RetroUtils的工具类(封装)public class RetroUtils { public static RetroApi RETROAPI(){ OkHttpClient client = new OkHttpClient.Builder() .connectTimeout(5, TimeUnit.SECONDS) .readTimeout(5,TimeUnit.SECONDS) .build(); Retrofit retrofit = new Retrofit.Builder() .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .baseUrl(RetroApi.BEAN) .build(); RetroApi retroApi = retrofit.create(RetroApi.class); return retroApi; } }
重点MVPview层public interface View_Shou { void succeed(Bean bean); }
public interface Gong_Shou<T> {编写公共的类最大程度防止内存泄露public void onAttach(T View_Shou); public void onDeattch(); }model层(获取网络请求)public class Model_Shou { public void ModelInterface(){ RetroUtils.RETROAPI().getBean().subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Observer<Bean>() { @Override public void onCompleted() { } @Override public void onError(Throwable e) { } @Override public void onNext(Bean bean) { modelInterface.onSucceed(bean); } }); } public interface ModelInterface{ void onSucceed(Bean bean); } public ModelInterface modelInterface; public void setModelInterface(ModelInterface modelInterface) { this.modelInterface = modelInterface; } }presenter层(获取网络请求)public class Presenter_Shou implements Model_Shou.ModelInterface,Gong_Shou<View_Shou> { private WeakReference<View_Shou> weak; private final Model_Shou model_shou; public Presenter_Shou(View_Shou view1) { this.model_shou = new Model_Shou(); onAttach(view1); model_shou.setModelInterface(this); } public void getData(){ model_shou.ModelInterface(); } @Override public void onAttach(View_Shou view_shou) { weak = new WeakReference<View_Shou>(view_shou); } @Override public void onDeattch() { weak.clear(); } @Override public void onSucceed(Bean bean) { weak.get().succeed(bean); } }