//先创建一个工具类
public class RetrofitUtil {
private Retrofit retrofit;
private static RetrofitUtil in;
private RetrofitUtil(){
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient build = new OkHttpClient.Builder()
.readTimeout(60, TimeUnit.SECONDS)
.writeTimeout(60, TimeUnit.SECONDS)
.connectTimeout(60, TimeUnit.SECONDS)
.addNetworkInterceptor(new Logg())
.addInterceptor(httpLoggingInterceptor)
.build();
retrofit=new Retrofit.Builder()
.client(build)
.baseUrl("http://mobile.bwstudent.com/small/")//172.17.8.100
.addConverterFactory(GsonConverterFactory.create())//添加数据解析器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())//把解析好的数据使用Rxjava进行回调处理
.build();
}
/* private class getid implements Interceptor {
@Override
public Response intercept(Chain chain) throws IOException {
return null;
}
}*/
//创建单例模式
public static RetrofitUtil getin(){
if (in == null) {
in=new RetrofitUtil();
}
return in;
}
public Retrofit getRetrofit() {
return retrofit;
}
private class Logg implements Interceptor{
@Override
public Response intercept(Chain chain) throws IOException {
//获取数据库
LoginBeanDao loginDao;
List<LoginBean> list;
loginDao=DaoMaster.newDevSession(MyFresco.getContext(),LoginBeanDao.TABLENAME).getLoginBeanDao();
list=new ArrayList<>();
list.addAll(loginDao.loadAll());
//循环判断
for (int i = 0; i < list.size(); i++) {
LoginBean lo=list.get(i);
if (lo == null) {
return null;
}else{
if (lo.getSex()==1){
Request request = chain.request();
Request.Builder header = request.newBuilder()
.addHeader("userId", String.valueOf(list.get(i).getUserId()))
.addHeader("sessionId", list.get(i).getSessionId());
Request build = header.build();
Response response = chain.proceed(build);
Log.i("aaa", "intercept: "+list.get(i).getSessionId());
Log.i("aaa", "intercept: "+String.valueOf(list.get(i).getUserId()));
return response;
}
}
}
return null;
}
}
}
//创建一个basepresenter 然后其余的presenter的继承那个类,
public abstract class BasePresenter {
private View view;
public BasePresenter(View view) {
this.view = view;
}
boolean isRunning;
public void getData(final Object...ag){
if (isRunning)
return;
isRunning=true;
IRequest iRequest = RetrofitUtil.getin().getRetrofit().create(IRequest.class);
getModel(iRequest,ag)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.onErrorReturn(new Function<Throwable,Data>() {
@Override
public Data apply(Throwable o) throws Exception {
return new Data("5000",o.getMessage());
}
})
.subscribe(new Consumer<Data>() {
@Override
public void accept(Data data) throws Exception {
isRunning=false;
if (data.status.equals("0000")){
view.success(data.result,ag);
}else{
view.fild(data,ag);
}
}
});
}
abstract Observable getModel(IRequest iRequest, Object...ag);
public void ondesctry(){
if (view != null) {
view=null;
}
}
}