Retrofit
public class RetrofitUtils {
private static RetrofitUtils instence;
private final Retrofit retrofit;
//单例模式
public static RetrofitUtils getInstence() {
if (instence==null){
synchronized (RetrofitUtils.class){
if (instence==null){
instence=new RetrofitUtils();
}
}
}
return instence;
}
private RetrofitUtils(){
//日志拦截器
HttpLoggingInterceptor interceptor=new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
//初始化okhttp
OkHttpClient okHttpClient=new OkHttpClient.Builder()
.addInterceptor(interceptor)
.addNetworkInterceptor(interceptor)
.readTimeout(5,TimeUnit.SECONDS)
.connectTimeout(5, TimeUnit.SECONDS)
.writeTimeout(5, TimeUnit.SECONDS)
.build();
//初始化retrofit 一个是gson解析 一个是结合rxjava
retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl(Api.BASE_URL)
.client(okHttpClient)
.build();
}
public ShowApi showApi(){
return retrofit.create(ShowApi.class);
}
}
MVP
C层
public interface IContract {
//抽象类
public abstract class IPresenter{
public abstract void getList(String uri,HashMap<String, String> map);
public abstract void getTwoList(String uri,HashMap<String, String> map);
}
//Model层
interface IModel{
void getList(String uri, HashMap<String,String> map, ResponseCallBack callBack);
void getTwoList(String uri,HashMap<String, String> map,ResponseCallBack callBack);
}
interface IView{
void success(List<SBean.ResultBean> list);
void xsuccess(XBean xBean);
void failure(String error);
}
}
M层
public class IModel implements IContract.IModel {
private ShowApi showApi;
@Override
public void getList(String uri, HashMap<String, String> map, final ResponseCallBack callBack) {
showApi = RetrofitUtils.getInstence().showApi();
Call<SBean> sshow = showApi.sshow(uri, map);
sshow.enqueue(new Callback<SBean>() {
@Override
public void onResponse(Call<SBean> call, Response<SBean> response) {
if (callBack!=null){
List<SBean.ResultBean> result = response.body().getResult();
callBack.success(result);
}
}
@Override
public void onFailure(Call<SBean> call, Throwable t) {
if (callBack!=null){
callBack.failure(t.getMessage());
}
}
});
}
**P层**
public class IPresenter extends IContract.IPresenter {
private IModel model;
private IContract.IView view;
public IPresenter(IContract.IView view) {
this.view = view;
model=new IModel();
}
@Override
public void getList(String uri, HashMap<String, String> map) {
if (model!=null){
model.getList(uri, map, new ResponseCallBack() {
@Override
public void success(List<SBean.ResultBean> list) {
if (view!=null){
view.success(list);
}
}
@Override
public void xsuccess(XBean xBean) {
}
@Override
public void failure(String error) {
if (view!=null){
view.failure(error);
}
}
});
}
}