HttpInterface.java 9.34 KB
package com.huaheng.mes.https;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.huaheng.mes.MESApplication;
import com.huaheng.mes.bean.Constant;
import com.huaheng.mes.https.convert.ResponseConverterFactory;
import com.huaheng.mes.util.MESUtils;
import com.huaheng.mes.util.MESlog;

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 HttpService httpService;

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

    public HttpInterface() {
        MESlog.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);
                        }
                        MESApplication.setOkhttpCookie(cookieStr);
                    }
                    return resp;
                }
            });
            clientBuilder.interceptors().add(new Interceptor() {
                @Override
                public Response intercept(Chain chain) throws IOException {
                    // 设置 Cookie
                    String cookieStr = MESApplication.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("token",MESApplication.getToken())
                            .addHeader("accept", "application/json").build();
                    return chain.proceed(request);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        String url = MESUtils.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<>();
        MESlog.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 login(Subscriber<ArrayList<String>> subscriber, String userName, String password) {
        JSONObject json = new JSONObject();
        try {
            json.put("code", userName);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MESlog.d("login :" + json.toString());
        MESApplication.setOkhttpCookie(null);
        RequestBody formBody = RequestBody.create(JSON, json.toString());
        Observable observable = httpService.login(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);
    }


}