封装

package kk.com.android_wdsc.utils.netutils;

import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import kk.com.android_wdsc.httpservice.BaseService;
import kk.com.android_wdsc.utils.mutils.LogeUtils;
import kk.com.android_wdsc.utils.mutils.MyApplication;
import okhttp3.OkHttpClient;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;


public class RetrofitUtils {

    /*请求码*/
    private String INTENRNAL_SERVER_ERROR ="服务器执行请求的时候出错了 ";
    private String UNAVAILABLE ="服务器超负载或正停机维护,无法处理请求 ";
    private String BAD_REQUEST ="请求报文存在语法错误或参数错误";
    private String UNAUTHORIZED ="HTTP认证信息或者是认证失败了 ";
    private String FORBIDDEN ="请求资源的访问被服务器拒绝了";
    private String NOTFOUND ="服务器找不到你请求的资源";

    //http://172.17.8.100/small/user/v1/login
    private  String baseUrl = "http://mobile.bwstudent.com/";
    private Map<String,String> headMap = new HashMap<>();
    private OkHttpClient client;
    private static RetrofitUtils retrofitUtils;
    private Retrofit retrofit;
    private SharedPreferences preferences;

    /*加入有多个baseUrl,可以动态修改*/
    public RetrofitUtils setBaseUrl(String baseUrl){
        this.baseUrl = baseUrl;
        return this;
    }

    public static RetrofitUtils getInstance(){
        if (retrofitUtils == null){
            retrofitUtils = new RetrofitUtils();
        }
        return retrofitUtils;
    }

    /*设置统一请求头参数Map<String,String> headMap*/
    public RetrofitUtils head(boolean b){
            String userId = MyApplication.getContext().getSharedPreferences("User", Context.MODE_PRIVATE).getString("userId", null);
            String sessionId = MyApplication.getContext().getSharedPreferences("User", Context.MODE_PRIVATE).getString("sessionId", null);
        if (b){
            headMap.put("userId",userId);
            headMap.put("sessionId",sessionId);
        }else {
            headMap.clear();
        }
        return this;
    }


    /*
     * 创建实列
     * */
    public  RetrofitUtils get(int type,String url,Map<String,String> map,CallBack callBack){
        loggingInterceptor(map);
        Observable<ResponseBody> ob = getService().get(url,headMap,map);
        subscribeSend(type,ob,callBack);
        return this;
    }
    public RetrofitUtils post(int type,String url,Map<String,String> map,CallBack callBack){
        loggingInterceptor(map);
        Observable<ResponseBody> ob = getService().post(url,headMap, map);
        subscribeSend(type,ob ,callBack);
        return this;
    }
    public RetrofitUtils put(int type,String url,Map<String,String> map,CallBack callBack){
        loggingInterceptor(map);
        Observable<ResponseBody> ob = getService().put(url,headMap, map);
        subscribeSend(type,ob ,callBack);
        return this;
    }
    public RetrofitUtils delete(int type,String url,Map<String,String> map,CallBack callBack){
        loggingInterceptor(map);
        Observable<ResponseBody> ob = getService().delete(url,headMap, map);
        subscribeSend(type,ob,callBack);
        return this;
    }
    //拦截器
    private void loggingInterceptor(Map<String,String> map) {
        if (map == null){
            map = new HashMap<>();
        }
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        client = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .readTimeout(5,TimeUnit.SECONDS)
                .connectTimeout(5,TimeUnit.SECONDS)
                .writeTimeout(5,TimeUnit.SECONDS)
                .build();
    }
    //订阅
    private void subscribeSend(final int type, final Observable<ResponseBody> ob, final CallBack callBack) {
        ob.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ObserverIml<ResponseBody>() {
                    @Override
                    public void onNext(ResponseBody responseBody) {
                        try {
                            String data = responseBody.string();
                               callBack.onSuccess(type,data);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void one rror(Throwable e) {
                        String message = e.getMessage();

                        switch (e.getMessage()){
                              case "HTTP 503 ":
                                  callBack.onFail(type,UNAVAILABLE);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                  break;
                              case "HTTP 500 ":
                                  callBack.onFail(type,INTENRNAL_SERVER_ERROR);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                    break;
                              case "HTTP 404 ":
                                  callBack.onFail(type,NOTFOUND);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                  break;
                              case "HTTP 403 ":
                                  callBack.onFail(type,FORBIDDEN);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                  break;
                              case "HTTP 401 ":
                                  callBack.onFail(type,UNAUTHORIZED);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                  break;
                              case "HTTP 400 ":
                                  callBack.onFail(type,BAD_REQUEST);
                                  LogeUtils.e("["+message+"]"+"["+UNAVAILABLE+"]");
                                  break;
                                  default:
                                      callBack.onFail(type,e.getMessage()+":其他异常");
                          }
                    }
                });
    }
    private BaseService getService() {
        retrofit = new Retrofit.Builder()
                .baseUrl(baseUrl)
                .client(client)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        BaseService baseService = retrofit.create(BaseService.class);
        return baseService;
    }
    //返回JavaBean
    public interface CallBack<T> {
        void onSuccess(int type,String t);
        void onFail(int type,String error);
    }

}
package kk.com.android_wdsc.httpservice;

/*
 *created by 王克强
 * on 2019/4/16
 */public class ServiceUser {
    /*登录small/user/v1/login*/
    public static String logein = "small/user/v1/login";
    /*:注册 http://172.17.8.100/small/user/v1/register*/
    public static String register = "small/user/v1/register";
    /*首页  small/commodity/v1/commodityList*/
    public static String commodityList = "small/commodity/v1/commodityList";
    /*搜索 small/commodity/v1/findCommodityByKeyword*/
    public static String findCommodityByKeyword = "small/commodity/v1/findCommodityByKeyword";
    /*banner轮播 small/commodity/v1/bannerShow*/
    public static String bannerShow = "small/commodity/v1/bannerShow";
    /*二级类目商品  http://172.17.8.100/small/commodity/v1/findCommodityListByLabel*/
    public static String findCommodityListByLabel = "small/commodity/v1/findCommodityListByLabel";
    /*商品详情  small/commodity/v1/findCommodityDetailsById*/
    public static String findCommodityDetailsById = "small/commodity/v1/findCommodityDetailsById";
    /*商品评价   http://172.17.8.100/small/commodity/v1/CommodityCommentList*/
    public static String CommodityCommentList = "small/commodity/v1/CommodityCommentList";
    /*同步购物车 small/order/verify/v1/syncShoppingCart*/
    public static String syncShoppingCart = "small/order/verify/v1/syncShoppingCart";
    /*我的圈子  small/circle/v1/findCircleList*/
    public static String findCircleList = "small/circle/v1/findCircleList";
    /*我的资料 small/user/verify/v1/getUserById*/
    public static String getUserById = "small/user/verify/v1/getUserById";
    /*我的足迹 small/commodity/verify/v1/browseList*/
    public static String browseList = "small/commodity/verify/v1/browseList";
    /*我的钱包 small/user/verify/v1/findUserWallet*/
    public static String findUserWallet = "small/user/verify/v1/findUserWallet";
    /*我的收货地址 small/user/verify/v1/receiveAddressList*/
    public static String receiveAddressList = "small/user/verify/v1/receiveAddressList";
    /*新增收货地址  small/user/verify/v1/addReceiveAddress*/
    public static String addReceiveAddress = "small/user/verify/v1/addReceiveAddress";
    /*设置默认收货地址 small/user/verify/v1/setDefaultReceiveAddress*/
    public static String setDefaultReceiveAddress = "small/user/verify/v1/setDefaultReceiveAddress";
    /*修改收货信息  small/user/verify/v1/changeReceiveAddress*/
    public static String changeReceiveAddress = "small/user/verify/v1/changeReceiveAddress";
}

 

上一篇:leetcode 23.合并K个排序链表


下一篇:放大镜效果