RxJava与OkHttp的封装

//工具类

public class RetrofitUtil {
    public static OkHttpClient okHttpClient;
    public static ApiService apiService;


    static {
        getOkHttpClient();
    }


    public static OkHttpClient getOkHttpClient(){
        if(okHttpClient == null){
            synchronized (OkHttpClient.class) {
                if(okHttpClient == null){
                    File fileDir = new File(Environment.getExternalStorageDirectory(), "cache");
                    long fileSize = 10 * 1024 * 1024;
                    okHttpClient = new OkHttpClient.Builder()
                            .connectTimeout(15, TimeUnit.SECONDS)
                            .readTimeout(15, TimeUnit.SECONDS)
                            .writeTimeout(15, TimeUnit.SECONDS)
                            .addInterceptor(new CommonParamsInterceptor())
                            .cache(new Cache(fileDir, fileSize))
                            .build();
                }
            }
        }
        return okHttpClient;
    }


    public static ApiService getApiService(String url){
        if(apiService == null){
            synchronized (OkHttpClient.class) {
                apiService = createApiService(ApiService.class,url);
            }
        }
        return apiService;
    }


    private static T createApiService(Class tClass, String url) {
        T t = new Retrofit.Builder()
                .baseUrl(url)
                .client(okHttpClient)
                .addConverterFactory(ScalarsConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build()
                .create(tClass);
        return t;
    }


    private static class CommonParamsInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            String method = request.method();
            String oldUrl = request.url().toString();
            Log.e("---拦截器",request.url()+"---"+request.method()+"--"+request.header("User-agent"));
            Map map = new HashMap<>();
            map.put("source","android");

            if ("GET".equals(method)){
                StringBuilder stringBuilder = new StringBuilder();
                stringBuilder.append(oldUrl);
                if (oldUrl.contains("?")){
                    if (oldUrl.indexOf("?") == oldUrl.length()-1){
                    }else {
                        stringBuilder.append("&");
                    }
                }else {
                    stringBuilder.append("?");
                }
                for (Map.Entry entry: map.entrySet()) {
                    stringBuilder.append(entry.getKey())
                            .append("=")
                            .append(entry.getValue())
                            .append("&");
                }
                if (stringBuilder.indexOf("&") != -1){
                    stringBuilder.deleteCharAt(stringBuilder.lastIndexOf("&"));
                }
                String newUrl = stringBuilder.toString();
                request = request.newBuilder()
                        .url(newUrl)
                        .build();
            }else if ("POST".equals(method)){
                RequestBody oldRequestBody = request.body();
                if (oldRequestBody instanceof FormBody){
                    FormBody oldBody = (FormBody) oldRequestBody;
                    FormBody.Builder builder = new FormBody.Builder();
                    for (int i=0;i                        builder.add(oldBody.name(i),oldBody.value(i));
                        Log.d("CommonParamsInterceptor", oldBody.name(i)+"===="+oldBody.value(i));

                    }
                    for (Map.Entry entry:map.entrySet()) {
                        builder.add(entry.getKey(),entry.getValue());
                    }
                    FormBody newBody = builder.build();
                    request = request.newBuilder()
                            .url(oldUrl)
                            .post(newBody)
                            .build();
                }
            }
            Response response = chain.proceed(request);
            return response;
        }
    }
}

//使用方法


public class ShopModel {
    private  Shop_inter shop_inter;

    public ShopModel(Shop_inter shop_inter) {
        this.shop_inter=shop_inter;
    }

    public void setUserData(String getCart_url, final int uid) {
       RetrofitUtil.getApiService(getCart_url).getCart(uid+"")
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.d("ShopModel", "e:" + e);
                    }

                    @Override
                    public void onNext(String s) {
                        Log.d("ShopModel", s);
                        ShopBean shopBean = new Gson().fromJson(s, ShopBean.class);
                        shop_inter.setSuccess(shopBean);
                    }
                });

    }
}

//接口

public interface ApiService {
    @FormUrlEncoded
    @POST("user/reg")
    Observable reg_url(@FieldMap Map map);

}

//依赖

//rxandroid
    compile 'io.reactivex:rxandroid:1.0.1'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.0.2'
    compile 'com.squareup.retrofit2:adapter-rxjava:2.0.2'
    compile 'com.squareup.retrofit2:converter-scalars:+'
    //gson
    compile 'com.google.code.gson:gson:2.2.4'

你可能感兴趣的:(android)