Retrofit+MVP框架封装记录篇
程序员文章站
2022-06-27 21:31:15
当下最流行的网络请求组合,retrofit2+okhttp+rxjava+mvp 这里是封装记录篇 首先分模块,比如登录 先来说封装后的使用 package com.fragmentapp.login.presenter; import android.util.Log; import com.fr ......
当下最流行的网络请求组合,retrofit2+okhttp+rxjava+mvp
这里是封装记录篇
首先分模块,比如登录
先来说封装后的使用
package com.fragmentapp.login.presenter; import android.util.Log; import com.fragmentapp.base.BasePresenter; import com.fragmentapp.http.BaseObserver; import com.fragmentapp.http.BaseResponses; import com.fragmentapp.login.bean.LoginDataBean; import com.fragmentapp.login.imple.ILoginModel; import com.fragmentapp.login.imple.ILoginView; import com.fragmentapp.login.model.LoginModel; /** * Created by liuzhen on 2017/11/3. */ public class LoginPresenter extends BasePresenter { private ILoginView view; private ILoginModel model; public LoginPresenter(ILoginView view){ this.view = view; model = new LoginModel(); } public void login(String username,String pwd){ model.login(observer,username,pwd); } BaseObserver<BaseResponses<LoginDataBean>> observer = new BaseObserver<BaseResponses<LoginDataBean>>(){ @Override public void onNextResponse(BaseResponses<LoginDataBean> loginDataBean) { Log.e("token",loginDataBean.getData().getHCACCESSTOKEN()+""); view.success(loginDataBean.getData()); } @Override public void onErrorResponse(BaseResponses<LoginDataBean> loginDataBean) { view.error(); } @Override public void onNetWorkError(String val) { view.error(); } }; }Presenter
通过p层的接口来交互,model去访问网络请求,然后返回结果回调返回到view层去刷新
这里自定义了一个base的obsever类,避免多次的传递接口
model则负责调用网络请求了
package com.fragmentapp.login.model; import com.fragmentapp.http.BaseObserver; import com.fragmentapp.http.BaseResponses; import com.fragmentapp.http.RetrofitHelper; import com.fragmentapp.login.bean.LoginDataBean; import com.fragmentapp.login.imple.ILoginModel; import java.util.HashMap; import java.util.Map; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * Created by liuzhen on 2017/11/7. */ public class LoginModel implements ILoginModel { @Override public void login(final BaseObserver<BaseResponses<LoginDataBean>> observer,String username,String pwd) { Map<String, String> map = new HashMap<>(); map.put("account[username]", username); map.put("account[password]", pwd); RetrofitHelper.getInstance().getService() .login(map) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(observer); } }View Code
view层的回调也只有两个接口,可以根据自己的需求添加
package com.fragmentapp.login.imple; import com.fragmentapp.login.bean.LoginDataBean; /** * Created by liuzhen on 2017/11/6. */ public interface ILoginView { void success(LoginDataBean dataBean); void error(); }View Code
访问网络后直接在activity里处理回调的结果刷新界面等
这里的retrofit的访问url是用的添加头部tag来达到动态访问替换baseurl的目的
package com.fragmentapp.http; import android.util.Log; import com.fragmentapp.BuildConfig; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.io.IOException; import java.util.List; import java.util.concurrent.TimeUnit; import okhttp3.HttpUrl; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Retrofit; import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; /** * Created by liuzhen on 2017/11/3. */ public class RetrofitHelper { private static final String BASE_URL_USER = "http://testapi.hanmaker.com"; private static final String BASE_URL_PAY = "https://www.222.com/"; private static final long TIME_OUT = 5000; private RetrofitHelper(){} private static class SingleHolder { private static final RetrofitHelper INSTANCE = new RetrofitHelper(); } public static final RetrofitHelper getInstance() { return SingleHolder.INSTANCE; } private static final long DEFAULT_TIMEOUT = 15L; final static Gson gson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .serializeNulls()// 调用serializeNulls方法,改变gson对象的默认行为,null值将被输出 .create(); //addInterceptor:设置应用拦截器,可用于设置公共参数,头信息,日志拦截等 //addNetworkInterceptor:网络拦截器,可以用于重试或重写 //setLevel NONE(不记录) BASIC(请求/响应行) HEADER(请求/响应行 + 头) BODY(请求/响应行 + 头 + 体) //cookieJar:保持在同一个会话里面 //TimeUnit.SECONDS秒做单位 private static OkHttpClient okHttpClient = new OkHttpClient.Builder() .writeTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .connectTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .readTimeout(DEFAULT_TIMEOUT, TimeUnit.SECONDS) .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)) .retryOnConnectionFailure(true)//错误重联 .addInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { //获取request Request request = chain.request(); if (BuildConfig.DEBUG) { // Log.e("request",request.toString()); } //获取request的创建者builder Request.Builder builder = request.newBuilder(); //从request中获取headers,通过给定的键url_name List<String> headerValues = request.headers("url_name"); if (headerValues != null && headerValues.size() > 0) { //如果有这个header,先将配置的header删除,因此header仅用作app和okhttp之间使用 builder.removeHeader("url_name"); //匹配获得新的BaseUrl String headerValue = headerValues.get(0); HttpUrl newBaseUrl = null; if ("user".equals(headerValue)) { newBaseUrl = HttpUrl.parse(BASE_URL_USER); } else if ("pay".equals(headerValue)) { newBaseUrl = HttpUrl.parse(BASE_URL_PAY); } else{ newBaseUrl = HttpUrl.parse(BASE_URL_USER); } //从request中获取原有的HttpUrl实例oldHttpUrl HttpUrl oldHttpUrl = request.url(); //重建新的HttpUrl,修改需要修改的url部分 HttpUrl newFullUrl = oldHttpUrl .newBuilder() .scheme(newBaseUrl.scheme())//设置网络协议 .host(newBaseUrl.host())//更换主机名 .port(newBaseUrl.port())//更换端口 .build(); //重建这个request,通过builder.url(newFullUrl).build(); //然后返回一个response至此结束修改 return chain.proceed(builder.url(newFullUrl).build()); } else { return chain.proceed(request); } } }) .build(); private static Retrofit retrofit = null; private static <T> T createApi(Class<T> clazz) { retrofit = new Retrofit.Builder() .baseUrl(BASE_URL_USER) .client(okHttpClient) .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) .addConverterFactory(GsonConverterFactory.create(gson)) .build(); return retrofit.create(clazz); } private RetrofitService service = null; public RetrofitService getService(){ if (service == null) service = createApi(RetrofitService.class); return service; } }View Code
然后接口参数采用map的方式添加,个人感觉一个个分开来跟烦,每次都得改service类
然后observable套用了一层类型,这里主要是后台数据格式吭,可以去掉
package com.fragmentapp.http; /** * Created by liuzhen on 2017/11/3. */ public class BaseResponses<T> { private String info; private int status; private T data; public String getInfo() { return info; } public void setInfo(String info) { this.info = info; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public T getData() { return data; } public void setData(T data) { this.data = data; } }View Code
然后是base的observer类,在里面根据自己的业务去回调自定义的接口,这样就不用每次重载这么多的方法了
package com.fragmentapp.http; import android.os.Looper; import android.util.Log; import io.reactivex.Observer; import io.reactivex.disposables.Disposable; /** * Created by liuzhen on 2017/11/3. */ public abstract class BaseObserver<T extends BaseResponses> implements Observer<T> { String TAG = getClass().getSimpleName(); @Override public void onSubscribe(Disposable d) { Log.e(TAG, "onSubscribe"); } @Override public void onNext(T t) { Log.e(TAG, "onNext"+t); if (t.getStatus() == 200) { onNextResponse(t); } else { Log.e(TAG, "ErrorStatus:" + t.getStatus() + "ErrorInfo" + t.getInfo()); onErrorResponse(t); } } @Override public void onError(Throwable e) { Log.e(TAG, "onError" + e.toString()); onNetWorkError("onError 网络超时,请重新尝试--"+e.getMessage()); if (Looper.myLooper() == null) { Looper.prepare(); Log.e(TAG,"onError 网络超时,请重新尝试"); Looper.loop(); } } @Override public void onComplete() { Log.e(TAG, "onComplete"); } /**返回成功*/ public abstract void onNextResponse(T t); /**接口失败信息*/ public abstract void onErrorResponse(T t); /**网络错误*/ public abstract void onNetWorkError(String val); }View Code
这个没啥好说的了
GitHub:https://github.com/1024477951/FragmentApp
上一篇: golang 变量定义