HttpInterface2.java 11.2 KB
package com.huaheng.mmsrf.https;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.huaheng.mmsrf.WMSApplication;
import com.huaheng.mmsrf.bean.ApkInfo;
import com.huaheng.mmsrf.bean.BillsInfo;
import com.huaheng.mmsrf.bean.CircleBean;
import com.huaheng.mmsrf.bean.CompanyInfo;
import com.huaheng.mmsrf.bean.Constant;
import com.huaheng.mmsrf.bean.DictData;
import com.huaheng.mmsrf.bean.GoodsInfo;
import com.huaheng.mmsrf.bean.InventoryDetail;
import com.huaheng.mmsrf.bean.InventoryDetails;
import com.huaheng.mmsrf.bean.InventoryTransaction;
import com.huaheng.mmsrf.bean.Location;
import com.huaheng.mmsrf.bean.LoginBean;
import com.huaheng.mmsrf.bean.Material;
import com.huaheng.mmsrf.bean.MaterialInfo;
import com.huaheng.mmsrf.bean.MaterialType;
import com.huaheng.mmsrf.bean.Materialforecast;
import com.huaheng.mmsrf.bean.MobileInventory;
import com.huaheng.mmsrf.bean.MobileTask;
import com.huaheng.mmsrf.bean.ModulesBean;
import com.huaheng.mmsrf.bean.PickingResult;
import com.huaheng.mmsrf.bean.Receipt;
import com.huaheng.mmsrf.bean.ReceiptBill;
import com.huaheng.mmsrf.bean.ReceiptHeader;
import com.huaheng.mmsrf.bean.ReceiptInfo;
import com.huaheng.mmsrf.bean.ReceiptType;
import com.huaheng.mmsrf.bean.SchedulerDetail;
import com.huaheng.mmsrf.bean.SchedulerHeader;
import com.huaheng.mmsrf.bean.SchedulerTransaction;
import com.huaheng.mmsrf.bean.ScherdulerDetailData;
import com.huaheng.mmsrf.bean.ScherdulerHeaderData;
import com.huaheng.mmsrf.bean.Shipment;
import com.huaheng.mmsrf.bean.ShipmentBill;
import com.huaheng.mmsrf.bean.ShipmentHeader;
import com.huaheng.mmsrf.bean.ShipmentMaterial;
import com.huaheng.mmsrf.bean.ShipmentMaterialDetail;
import com.huaheng.mmsrf.bean.ShipmentTaskModel;
import com.huaheng.mmsrf.bean.ShipmentType;
import com.huaheng.mmsrf.bean.SysUser;
import com.huaheng.mmsrf.bean.SysUserBean;
import com.huaheng.mmsrf.bean.TaskDetailBean;
import com.huaheng.mmsrf.bean.TaskHeader;
import com.huaheng.mmsrf.bean.Technology;
import com.huaheng.mmsrf.bean.TechnologyData;
import com.huaheng.mmsrf.bean.TodayInfo;
import com.huaheng.mmsrf.bean.TokenBean;
import com.huaheng.mmsrf.bean.UserBean;
import com.huaheng.mmsrf.bean.Working;
import com.huaheng.mmsrf.https.convert.ResponseConverterFactory;
import com.huaheng.mmsrf.util.WMSLog;
import com.huaheng.mmsrf.util.WMSUtils;

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.Set;
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 okhttp3.internal.http2.ErrorCode;
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;

import static com.huaheng.mmsrf.util.WMSUtils.jsonToMap;

public class HttpInterface2 {

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

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

    public HttpInterface2() {
        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(HttpConstant.CONNECT_TIMEOUT, TimeUnit.SECONDS)
                    .writeTimeout(HttpConstant.WRITE_TIMEOUT, TimeUnit.SECONDS)
                    .readTimeout(HttpConstant.READ_TIMEOUT, TimeUnit.SECONDS)
                    .sslSocketFactory(getSSLSocketFactory())
                    .hostnameVerifier(new HostnameVerifier() {
                        @Override
                        public boolean verify(String hostname, SSLSession session) {

                            return true;
                        }
                    });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(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("X-Access-Token",WMSApplication.getToken())
                            .addHeader("accept", "application/json").build();
                    return chain.proceed(request);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        String url = WMSUtils.getData(Constant.NETWORK);
        retrofit = new Retrofit.Builder()
                .client(clientBuilder.build())
                .addConverterFactory(ResponseConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .baseUrl(HttpConstant.URL2)
                .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) {
        httpService = retrofit.create(HttpService.class);
    }

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


    public void getUpdateApkInfo(Subscriber<ApkInfo> subscriber, String pkgName, String versionCode) {
        JSONObject object = new JSONObject();
        try {
            object.put("pkgName", pkgName);
            object.put("versionCode", versionCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
        WMSLog.d("getUpdateApkInfo:" + object.toString());
        RequestBody formBody = RequestBody.create(JSON, object.toString());
        Observable observable = httpService.getUpdateApkInfo(formBody)
                .map(new ApiResponseFunc<ApkInfo>());

        toSubscribe(observable, subscriber);
    }

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

        @Override
        public T call(ApiResponse2<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) {
        WMSUtils.startTime = System.currentTimeMillis();
        observable
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }


}