当前位置: 代码迷 >> 综合 >> RxJava+Retrofit通用封装
  详细解决方案

RxJava+Retrofit通用封装

热度:84   发布时间:2023-12-06 09:09:40.0
public interface Api {//获得购物车的接口
    public static final String GETCARS = "https://www.zhaoapi.cn/product/getCarts";//Boss
    public static final String BASE = "http://120.27.23.105/";//Login
    public static final String Login = "user/login";public static final String zhuce = "user/reg";//创建订单接口
    public static final String CREATEORDER = "https://www.zhaoapi.cn/product/createOrder";//获取订单列表接口
    public static final String GETORDERS = "https://www.zhaoapi.cn/product/getOrders";//.修改订单状态
    public static final String UPDATEORDER = "https://www.zhaoapi.cn/product/updateOrder";
}
public interface ApiService {@GET
    Observable<String> get(@Url String url, @QueryMap Map<String, String> map);@FormUrlEncoded
    @POST
    Observable<String> post(@Url String url, @FieldMap Map<String, String> map);}
public abstract class BaseObserver<T> implements Observer<String> {@Override
    public void onSubscribe(Disposable d) {}@Override
    public void onNext(String s) {try {Type genType = getClass().getGenericSuperclass();Type[] params = ((ParameterizedType) genType).getActualTypeArguments();Class entityClass = (Class) params[0];Gson gson = new Gson();T t = (T)gson.fromJson(s,entityClass);success(t);} catch (Exception e) {failure(1001);e.printStackTrace();}}@Override
    public void onError(Throwable e) {try {if(e != null){if(e instanceof HttpException){failure(HTTP_ERROR);} else if(e instanceof SocketException){failure(NET_WORK_ERROR);}else {failure(UNKNOW_ERROR);}}else {failure(UNKNOW_ERROR);}e.printStackTrace() ;} catch (Exception e1) {failure(UNKNOW_ERROR);e1.printStackTrace();}}@Override
    public void onComplete() {}//

    /**
     * code
     *  1000 UNKNOW_ERROR 未知错误
     *  1001 json 转化异常  parse error
     *  1002 当前网络不可用     java.net.SocketException: Network is unreachable  超时
     *  1003 服务器不可用 401 402 403 500 502 503 504
     * @param code
     */

    public static final int UNKNOW_ERROR = 1000;public static final int JSON_FORMAT_ERROR = 1001;public static final int NET_WORK_ERROR = 1002;public static final int HTTP_ERROR = 1003;public abstract void success(T t);public abstract void failure(int code);}
public class LoginModule {public void getData(Map<String, String> map, final LoginModuleListener loginModuleListener){RetrofitManager.post(Api.Login, map, new BaseObserver<LoginBean>() {@Override
            public void success(LoginBean loginBean) {if(loginModuleListener!=null){loginModuleListener.success(loginBean);}}@Override
            public void failure(int code) {Log.d("TAG",code+"");}});}public interface LoginModuleListener{void success(LoginBean loginBean);}}



public class RetrofitManager {public static OkHttpClient client = new OkHttpClient.Builder()//OK自定义拦截器
            .addInterceptor(new LoggingInterceptor()).build();public static com.hss.net.ApiService apiService = new Retrofit.Builder().baseUrl(com.hss.net.Api.BASE).addCallAdapterFactory(RxJava2CallAdapterFactory.create()).addConverterFactory(ScalarsConverterFactory.create()).client(client).build().create(ApiService.class);public static void get(String url, Map<String,String> map, Observer observer){apiService.get(url,map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);}public static void post(String url,Map<String,String> map,Observer observer){apiService.post(url,map).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(observer);}}



public class LoggingInterceptor implements Interceptor {@Override
    public Response intercept(Chain chain) throws IOException {Request request = chain.request();//GET自定义拦截器
        if (request.method().equals("GET")) {HttpUrl url = request.url().newBuilder().addQueryParameter("source", "android").build();//添加请求头
            Request newrequest = request.newBuilder().url(url).build();return chain.proceed(newrequest);}else {//POST自定义拦截器
            String url = request.url().url().toString();url+="&source=android";Request newRequset = request.newBuilder().url(url).build();return chain.proceed(newRequset);}}
}