HttpInterface.java 14.3 KB
package com.huaheng.wms.https;

import android.text.TextUtils;
import android.util.Log;

import com.huaheng.wms.WMSApplication;
import com.huaheng.wms.WMSLog;
import com.huaheng.wms.collectgoods.BillsInfo;
import com.huaheng.wms.collectgoods.CollectGoodsActivity;
import com.huaheng.wms.collectgoods.ColletGoodService;
import com.huaheng.wms.collectgoods.GoodsInfo;
import com.huaheng.wms.collectgoods.ReceiptInfo;
import com.huaheng.wms.https.convert.ResponseConverterFactory;
import com.huaheng.wms.login.LoginService;
import com.huaheng.wms.login.UserBean;
import com.huaheng.wms.login.WareHouseBean;
import com.huaheng.wms.menu.ModulesBean;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.lang.reflect.Array;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class HttpInterface {

    public final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static HttpInterface insstance = null;
    private Retrofit retrofit;
    private Map<String, Object> paramMap;
    private OkHttpClient.Builder clientBuilder;

    private LoginService loginService;                      //  登录
    private ColletGoodService colletGoodService;

    public static HttpInterface getInsstance() {
        WMSLog.d("HttpInterface insstance:" +insstance);
        if(insstance == null) {
            insstance = new HttpInterface();
        }
        return insstance;
    }

    public HttpInterface() {
        WMSLog.d("HttpInterface");
        TrustManager[] trustManager = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] chain, String authType) throws
                            CertificateException {
                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] chain, String authType) throws
                            CertificateException {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;    // 返回null
                    }
                }
        };

        clientBuilder = new OkHttpClient.Builder();
        try {
            clientBuilder
                    .connectTimeout(30, TimeUnit.SECONDS)
//                    .addInterceptor(new UserEntityInterceptor())
//                    .addInterceptor(new LoggerInterceptor("", true))
                    .sslSocketFactory(getSSLSocketFactory())
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {

                            return true;
                        }
                    });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Interceptor.Chain chain) throws IOException {
                    // 获取 Cookie
                    Response resp = chain.proceed(chain.request());
                    List<String> cookies = resp.headers("Set-Cookie");
                    String cookieStr = "";
                    if (cookies != null && cookies.size() > 0) {
                        for (int i = 0; i < cookies.size(); i++) {
                            cookieStr += cookies.get(i);
                        }
                        WMSLog.d("setOkhttpCookie :" + cookieStr);
                        WMSApplication.setOkhttpCookie(cookieStr);
                    }
                    return resp;
                }
            });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    // 设置 Cookie
                    String cookieStr = WMSApplication.getOkhttpCookie();
                    WMSLog.d("getOkhttpCookie :" + cookieStr);
                    if (!TextUtils.isEmpty(cookieStr)) {
                        return chain.proceed(chain.request().newBuilder().header("Cookie", cookieStr).build());
                    }
                    return chain.proceed(chain.request());
                }
            });
//                    .cookieJar(cookieJar);
        } catch (Exception e) {
            e.printStackTrace();
        }

        retrofit = new Retrofit.Builder()
                .client(clientBuilder.build())
//                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ResponseConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(HttpConstant.URL)
                .build();

        paramMap = new HashMap<>();
        WMSLog.d("initService");
        initService(retrofit);
    }

    private static SSLSocketFactory getSSLSocketFactory() throws Exception {
        //创建一个不验证证书链的证书信任管理器。
        final TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(
                    java.security.cert.X509Certificate[] chain,
                    String authType) throws CertificateException {
            }

            @Override
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[0];
            }
        }};

        // Install the all-trusting trust manager
        final SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
        // Create an ssl socket factory with our all-trusting manager
        return sslContext.getSocketFactory();
    }

    public void setBaseUrl(String url) {
        retrofit = new Retrofit.Builder()
                .client(clientBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(url)
                .build();
        initService(retrofit);
    }

    private void initService(Retrofit retrofit) {
        //  登录
        loginService = retrofit.create(LoginService.class);
        colletGoodService = retrofit.create(ColletGoodService.class);
    }

    public String getBaseUrl() {
        return retrofit.baseUrl().toString();
    }

    public void login(Subscriber<ArrayList<UserBean>> subscriber, String userName, String password) {
        JSONObject json = new JSONObject();
        try {
            json.put("code", userName);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        WMSApplication.setOkhttpCookie(null);
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = loginService.login(formBody)
                .map(new ApiResponseFunc<ArrayList<UserBean>>());

        toSubscribe(observable, subscriber);;
    }

    public void getModules(Subscriber<ArrayList<ModulesBean>> subscriber, String warehouseCode, int warehouseId) {
        JSONObject json = new JSONObject();
        try {
            json.put("warehouseId", warehouseId);
            json.put("warehouseCode", warehouseCode);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = loginService.getModules(formBody)
                .map(new ApiResponseFunc<ArrayList<ModulesBean>>());

        toSubscribe(observable, subscriber);
    }

    public void scanBill(Subscriber<ArrayList<ReceiptInfo>> subscriber, String code) {
        JSONObject json = new JSONObject();
        try {
            json.put("code", code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = colletGoodService.scanBill(formBody)
                .map(new ApiResponseFunc<ArrayList<ReceiptInfo>>());

        toSubscribe(observable, subscriber);
    }

    public void sanContainer(Subscriber<String> subscriber, String code) {
        JSONObject json = new JSONObject();
        try {
            json.put("code", code);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = colletGoodService.sanContainer(formBody)
                .map(new ApiResponseFunc<String>());

        toSubscribe(observable, subscriber);
    }

    public void saveBillByPiece(Subscriber<GoodsInfo> subscriber, String receiptContainerCode, String receiptDetailId) {
        JSONObject json = new JSONObject();
        try {
            json.put("receiptContainerCode", receiptContainerCode);
            json.put("receiptDetailId", receiptDetailId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = colletGoodService.saveBillByPiece(formBody)
                .map(new ApiResponseFunc<GoodsInfo>());

        toSubscribe(observable, subscriber);
    }

    public void saveBillByBulk(Subscriber<List<GoodsInfo>> subscriber, List<BillsInfo> billsInfos) {
        JSONArray array = new JSONArray();
        try {
            for (int i = 0; i < billsInfos.size(); i++) {
                JSONObject object = new JSONObject();
                object.put("receiptContainerCode", billsInfos.get(i).getReceiptContainerCode());
                object.put("receiptDetailId", billsInfos.get(i).getReceiptDetailId());
                object.put("qty", billsInfos.get(i).getQty());
                array.put(object);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        WMSLog.d("saveBillByBulk  array:" + array.toString());
        RequestBody formBody = RequestBody.create(JSON, array.toString());
        Observable observable = colletGoodService.saveBillByBulk(formBody)
                .map(new ApiResponseFunc<List<GoodsInfo>>());

        toSubscribe(observable, subscriber);
    }


 /*   private void commonPost(String url, RequestBody formBody) {
        OkHttpClient mOkHttpClient = new OkHttpClient.Builder()
                .readTimeout(HttpConstant.READ_TIMEOUT, TimeUnit.SECONDS)
                .writeTimeout(HttpConstant.WRITE_TIMEOUT, TimeUnit.SECONDS)
                .connectTimeout(HttpConstant.CONNECT_TIMEOUT, TimeUnit.SECONDS).build();
        Request request = null;
        String cookie = WMSApplication.getOkhttpCookie();
        if(cookie == null) {
            request = new Request.Builder()
                    .url(url)
                    .post(formBody)
                    .build();
        } else {
            request = new Request.Builder()
                    .addHeader("cookie",cookie)
                    .url(url)
                    .post(formBody)
                    .build();
        }
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                Headers headers = response.headers();
                List<String> cookies = headers.values("Set-Cookie");
                if (cookies.size() > 0) {
                    String session = cookies.get(0);
                    String result = session.substring(0, session.indexOf(";"));
                    WMSApplication.setOkhttpCookie(result);
                }
                WMSLog.d("onResponse str:" +  str);
            }
        });
        WMSLog.d("commonPost url:" +  url);
    }  */

    /**
     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
     *
     * @param <T> Subscriber真正需要的数据类型,也就是Data部分的数据类型
     */
    private class ApiResponseFunc<T> implements Func1<ApiResponse<T>, T> {

        @Override
        public T call(ApiResponse<T> apiResponse) {
            WMSLog.d("apiResponse:" + apiResponse);
//            WMSLog.d("getSession:" + apiResponse.getSession());
            WMSLog.d("getCode:" + apiResponse.getCode());
            WMSLog.d("getMsg:" + apiResponse.getMsg());
            if (!apiResponse.getCode().equals("200")) {
                throw new ApiException(apiResponse.getMsg());
            }

            if (apiResponse.getData() != null) {
                return apiResponse.getData();
            } else if (apiResponse.getSession() != null) {
                return apiResponse.getSession();
            }

            return null;
        }
    }

    private void toSubscribe(Observable observable, Subscriber subscriber) {
        observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }


}