Retrofit对OKhttp的封装

compile 'com.squareup.okhttp3:okhttp:3.4.1'  //Okhttp
    compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'//Retrofit2所需要的包
    compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'//ConverterFactory的Gson依赖包
    compile 'io.reactivex.rxjava2:rxjava:2.1.3'
    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'com.squareup.retrofit2:adapter-rxjava2:2.3.0'
    compile 'com.squareup.okhttp3:logging-interceptor:3.9.0' //日志拦截器
    //动态URL
    compile 'me.jessyan:retrofit-url-manager:1.1.0'
public class HttpCommonParamsInterceptor implements Interceptor {


    public static final String TAG = "HttpParamsInterceptor";

    private Builder.Type mType;

    private Map mParams;

    private HttpCommonParamsInterceptor() {

    }

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request request = chain.request();

        switch (mType) {
            case HEADER:
                request = addParams2Header(request, mParams);
                break;
            case QUERY_STRING:
                request = addParams2UrlQueryString(request, mParams);
                break;
            case FORM:
                request = addParams2FormBody(request, mParams);
                break;
            case AUTO: {
                String method = request.method();
                if (method.equalsIgnoreCase("get")) {
                    request = addParams2UrlQueryString(request, mParams);
                } else if (method.equalsIgnoreCase("post")) {
                    request = addParams2FormBody(request, mParams);
                }
            }
            break;
            default:
                throw new IllegalArgumentException("unknown type");
        }
        return chain.proceed(request);
    }

    private Request addParams2Header(Request request, Map mParams) {

        Set> entrySets = mParams.entrySet();
        Request.Builder builder = request.newBuilder();
        for (Map.Entry entry : entrySets) {
            builder.addHeader(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return builder.build();
    }

    private Request addParams2UrlQueryString(Request request, Map mParams) {

        HttpUrl httpUrl = request.url();
        HttpUrl.Builder builder = httpUrl.newBuilder();
        Set> entrySets = mParams.entrySet();
        for (Map.Entry entry : entrySets) {
            builder.addQueryParameter(entry.getKey(), String.valueOf(entry.getValue()));
        }
        return request.newBuilder()
                .url(builder.build())
                .build();
    }

    private Request addParams2FormBody(Request request, Map mParams) {

        RequestBody requestBody = request.body();
        if (requestBody instanceof FormBody) {
            FormBody formBody = (FormBody) requestBody;
            int size = formBody.size();

            TreeMap params = new TreeMap<>();
            for (int i = 0; i < size; i++) {
                String name = formBody.encodedName(i);
                String value = formBody.encodedValue(i);
                params.put(name, value);
            }


            // add mParams to params
            Set> entrySets = mParams.entrySet();
            for (Map.Entry entry : entrySets) {
                params.put(entry.getKey(), String.valueOf(entry.getValue()));
            }

            // convert params to new formBody
            FormBody.Builder builder = new FormBody.Builder();

            Set> newEnterySet = params.entrySet();
            for (Map.Entry entry : newEnterySet) {
                builder.add(entry.getKey(), entry.getValue());
            }

            // to new request
            return request.newBuilder().post(builder.build()).build();
        } else {
            Log.w(TAG, "RequestBody => " + request.body().getClass().getCanonicalName() + " Not Support Yet!");
        }


        return request;
    }


    public static class Builder {

        private Type mType;

        private Map mParams;

        public enum Type {
            /**
             * add params to header
             */
            HEADER,

            /**
             * add params to query string with urlencoded
             */
            QUERY_STRING,

            /**
             * add params to body according to form type
             */
            FORM,

            /**
             * only works for http GET & POST
             */
            AUTO,
        }

        public Builder() {
            mParams = new TreeMap<>();
        }


        public Builder type(Type type) {
            mType = type;
            return this;
        }

        public Builder params(String key, String value) {
            mParams.put(key, value);
            return this;
        }

        public Builder params(String key, Integer value) {
            mParams.put(key, value);
            return this;
        }

        public Builder params(String key, Double value) {
            mParams.put(key, value);
            return this;
        }

        public Builder params(Map map) {
            mParams.putAll(map);
            return this;
        }

        public HttpCommonParamsInterceptor build() {
            if (mType == null) {
                throw new IllegalArgumentException("must set type");
            }
            HttpCommonParamsInterceptor interceptor = new HttpCommonParamsInterceptor();
            interceptor.mType = mType;
            interceptor.mParams = mParams;
            return interceptor;
        }
    }

}

/**
 * 封装的公共参数
 */

public class QueryParam {


}

public class RxSchedulers {
    public static  ObservableTransformer io_main() {
        return new ObservableTransformer() {
            @Override
            public ObservableSource apply(Observable upstream) {
                return upstream
                        .subscribeOn(Schedulers.io())
                        .observeOn(AndroidSchedulers.mainThread());
            }
        };
    }
}
/**
 * 
 * 用于对Object进行解析并且转换成Map键值对的形式
 *
 * 
 * @version 1.0
 */
public class ObjectUtils {

    private static final String JAVAP = "java.";
    private static final String JAVADATESTR = "java.util.Date";

    /**
     * 获取利用反射获取类里面的值和名称
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static  Map objectToMap(Object obj) throws IllegalAccessException {
        Map map = new HashMap<>();
        Class clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            T value = (T) field.get(obj);
            map.put(fieldName, value);
        }
        if (BuildConfig.DEBUG){
            Log.d("ObjectUtils",map.toString());
        }
        return map;
    }

    /**
     * 利用递归调用将Object中的值全部进行获取
     *
     * @param timeFormatStr 格式化时间字符串默认2017-03-10 10:21
     * @param obj           对象
     * @param excludeFields 排除的属性
     * @return
     * @throws IllegalAccessException
     */
    public static Map objectToMapString(String timeFormatStr, Object obj, String... excludeFields) throws IllegalAccessException {
        Map map = new HashMap<>();

        if (excludeFields.length != 0) {
            List list = Arrays.asList(excludeFields);
            objectTransfer(timeFormatStr, obj, map, list);
        } else {
            objectTransfer(timeFormatStr, obj, map, null);
        }
        return map;
    }


    /**
     * 递归调用函数
     *
     * @param obj           对象
     * @param map           map
     * @param excludeFields 对应参数
     * @return
     * @throws IllegalAccessException
     */
    private static Map objectTransfer(String timeFormatStr, Object obj, Map map, List excludeFields) throws IllegalAccessException {
        boolean isExclude = false;
        //默认字符串
        String formatStr = "YYYY-MM-dd HH:mm:ss";
        //设置格式化字符串
        if (timeFormatStr != null && !timeFormatStr.isEmpty()) {
            formatStr = timeFormatStr;
        }
        if (excludeFields != null) {
            isExclude = true;
        }
        Class clazz = obj.getClass();
        //获取值
        for (Field field : clazz.getDeclaredFields()) {
            String fieldName = clazz.getSimpleName() + "." + field.getName();
            //判断是不是需要跳过某个属性
            if (isExclude && excludeFields.contains(fieldName)) {
                continue;
            }
            //设置属性可以被访问
            field.setAccessible(true);
            Object value = field.get(obj);
            Class valueClass = value.getClass();
            if (valueClass.isPrimitive()) {
                map.put(fieldName, value.toString());

            } else if (valueClass.getName().contains(JAVAP)) {//判断是不是基本类型
                if (valueClass.getName().equals(JAVADATESTR)) {
                    //格式化Date类型
                    SimpleDateFormat sdf = new SimpleDateFormat(formatStr);
                    Date date = (Date) value;
                    String dataStr = sdf.format(date);
                    map.put(fieldName, dataStr);
                } else {
                    map.put(fieldName, value.toString());
                }
            } else {
                objectTransfer(timeFormatStr, value, map, excludeFields);
            }
        }
        return map;
    }

}

public class API {
    public static String HOST="http://www.bwstudent.com";
}

public class RetrofitHelper {

    private static Retrofit retrofit;

    static {
        initRetrofit(API.HOST);
    }

    /**
     * 获取OkHttpClient
     *
     * @return
     */
    private static OkHttpClient getOkHttpClient() {

        //TODO 处理拦截器,自定义缓存,HTTP的一些参数设置
        OkHttpClient.Builder builder = RetrofitUrlManager
                .getInstance()
                .with(new OkHttpClient.Builder()) //RetrofitUrlManager 初始化
//                .readTimeout(30, TimeUnit.SECONDS)
//                .connectTimeout(30, TimeUnit.SECONDS)
                ;


        //只有再开发版本才打印log日志
        if (BuildConfig.DEBUG) {
            //TODO 日志拦截器
            builder.addInterceptor(new HttpLoggingInterceptor());
        }

        try {
            Map map= ObjectUtils.objectToMap(new QueryParam());//将类型转化为map集合
            HttpCommonParamsInterceptor commonParamsInterceptor = new HttpCommonParamsInterceptor.Builder()
                    .type(HttpCommonParamsInterceptor.Builder.Type.QUERY_STRING)
                    .params(map)
                    .build();
            builder.addInterceptor(commonParamsInterceptor);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return builder.build();
    }

    /**
     * 初始化Retrofit
     *
     * @param url
     */
    private static void initRetrofit(String url) {
        if (retrofit == null) {
            synchronized (Retrofit.class) {
                if (retrofit == null) {
                    retrofit = new Retrofit.Builder()
                            .baseUrl(url)
                            .client(getOkHttpClient())
                            .addConverterFactory(GsonConverterFactory.create())
                            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                            .build();
                }
            }
        }
    }

    public static ServiceApi getServiceAPI() {
        return createAPI(ServiceApi.class);
    }

  /*  public static SNSAPI getSNSAPI() {
        return createAPI(SNSAPI.class);
    }*/

    private static  T createAPI(Class clzss) {
        return retrofit.create(clzss);
    }

}

public interface ServiceApi {
}



你可能感兴趣的:(Retrofit对OKhttp的封装)