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

import android.text.TextUtils;

import com.huaheng.robot.WMSApplication;
import com.huaheng.robot.login.WorkStation;
import com.huaheng.robot.shipment.ShipmentBill;
import com.huaheng.robot.shipment.ShipmentService;
import com.huaheng.robot.shipment.ShipmentTaskModel;
import com.huaheng.robot.util.Constant;
import com.huaheng.robot.util.WMSUtils;
import com.huaheng.robot.https.convert.ResponseConverterFactory;
import com.huaheng.robot.login.LoginService;
import com.huaheng.robot.login.ModulesBean;
import com.huaheng.robot.login.UserBean;
import com.huaheng.robot.util.WMSLog;

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

import java.io.IOException;
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.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
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 ShipmentService shipmentService;                //  出库

    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);
                        }
                        WMSApplication.setOkhttpCookie(cookieStr);
                    }
                    return resp;
                }
            });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    // 设置 Cookie
                    String cookieStr = WMSApplication.getOkhttpCookie();
                    if (!TextUtils.isEmpty(cookieStr)) {
                        return chain.proceed(chain.request().newBuilder().header("Cookie", cookieStr).build());
                    }
                    return chain.proceed(chain.request());
                }
            });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    Request request = chain.request().newBuilder()
                            .addHeader("Content-Type", "application/json")
                            .addHeader("accept", "application/json").build();
                    return chain.proceed(request);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        String url = WMSUtils.getData(Constant.NETWORK);
        if(url != null) {
            retrofit = new Retrofit.Builder()
                    .client(clientBuilder.build())
                    .addConverterFactory(ResponseConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(url)
                    .build();
        } else {
            retrofit = new Retrofit.Builder()
                    .client(clientBuilder.build())
                    .addConverterFactory(ResponseConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .baseUrl(HttpConstant.URL)
                    .build();
        }

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

    public void  reset() {
        insstance = null;
    }

    private static SSLSocketFactory getSSLSocketFactory() throws Exception {
        //创建一个不验证证书链的证书信任管理器。
        final TrustManager[] trustAllCerts = 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 new 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);
        shipmentService = retrofit.create(ShipmentService.class);
//        colletGoodService = retrofit.create(ColletGoodService.class);
//        onshellService = retrofit.create(OnshellService.class);
//        pickingService = retrofit.create(PickingService.class);
//        inventoryQueryService = retrofit.create(InventoryQueryService.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 getAllWorkStation(Subscriber<ArrayList<WorkStation>> subscriber) {
        JSONObject json = new JSONObject();
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = loginService.getAllWorkStation(formBody)
                .map(new ApiResponseFunc<ArrayList<WorkStation>>());

        toSubscribe(observable, subscriber);
    }

    public void autoShipment(Subscriber<List<Integer>> subscriber,  List<ShipmentBill> shipmentBills) {
        String companyCode = WMSUtils.getData(Constant.CURREN_COMPANY_CODE, Constant.DEFAULT_COMPANY_CODE);
        String companyId = WMSUtils.getData(Constant.CURREN_COMPANY_ID, Constant.DEFAULT_COMPANY_ID);
        JSONArray array = new JSONArray();
        for(ShipmentBill shipmentBill : shipmentBills) {
            JSONObject object = new JSONObject();
            try {
                object.put("materialCode", shipmentBill.getMaterialCode());
                object.put("qty", shipmentBill.getQty());
                object.put("taskType", 400);
                object.put("location", shipmentBill.getLocation());
                object.put("companyCode", companyCode);
                object.put("companyId", companyId);
                object.put("point", shipmentBill.getPoint());
                array.put(object);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        WMSLog.d("autoShipment :" + array.toString());
        RequestBody formBody = RequestBody.create(JSON, array.toString());
        Observable observable = shipmentService.autoShipment(formBody)
                .map(new ApiResponseFunc<List<Integer>>());

        toSubscribe(observable, subscriber);
    }

    public void createShipTask(Subscriber<List<Integer>> subscriber, ShipmentTaskModel shipmentTaskCreateModel) {
        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        String companyCode = WMSUtils.getData(Constant.CURREN_COMPANY_CODE, Constant.DEFAULT_COMPANY_CODE);
        String companyId = WMSUtils.getData(Constant.CURREN_COMPANY_ID, Constant.DEFAULT_COMPANY_ID);
        for(int i = 0 ; i < shipmentTaskCreateModel.getShipmentContainerHeaderIds().length ;i++) {  //依次将数组元素添加进JSONArray对象中
            jsonArray.put(shipmentTaskCreateModel.getShipmentContainerHeaderIds()[i]);
        }
        try {
            json.put("shipmentContainerHeaderIds", jsonArray);
            json.put("taskType", shipmentTaskCreateModel.getTaskType());
            json.put("priority", shipmentTaskCreateModel.getPriority());
            json.put("companyCode", companyCode);
            json.put("companyId", companyId);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = shipmentService.createShipTask(formBody)
                .map(new ApiResponseFunc<List<Integer>>());

        toSubscribe(observable, subscriber);
    }

    public void executeList(Subscriber<String> subscriber, List<Integer> taskIdList) {
        JSONArray jsonArray = new JSONArray();
        for(Integer taskId : taskIdList) {
            JSONObject object = new JSONObject();
            try {
                object.put("taskId", taskId);
                jsonArray.put(object);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        WMSLog.d("executeList  :" + jsonArray.toString());
        RequestBody formBody = RequestBody.create(JSON, jsonArray.toString());
        Observable observable = shipmentService.executeList(formBody)
                .map(new ApiResponseFunc<String>());

        toSubscribe(observable, subscriber);
    }

    /**
     * 用来统一处理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) {
            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);
    }


}