package nckd.jimin.jyyy.bd.plugin.msg.ecology;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.GzipDecompressingEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import javax.security.cert.CertificateException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;

public class HttpUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    private static int default_connectionTimeout = Integer.getInteger("httpclient.connectionTimeout", 3000);
    private static int default_readTimeout = Integer.getInteger("httpclient.readTimeout", 5000);
    private static String SCHEME_HTTPS = "https";

    public static String postjson(String url, Map<String, String> header, String json) throws IOException {
        return postjson(url, header, json, default_connectionTimeout, default_readTimeout);
    }



    public static String postjson(String url, Map<String, String> header, String json, int connectionTimeout, int readTimeout) throws IOException {
        String CONTENT_TYPE_TEXT_JSON = "text/json;";
        String data = "";
        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        URI uri = post.getURI();
        if (SCHEME_HTTPS.equals(uri.getScheme())) {
            client = wrapperHttpClient(connectionTimeout, readTimeout);
            if (client == null) {
                return data;
            }
        } else {
            client = createHttpClient(connectionTimeout, readTimeout);
            HttpParams httpParams = client.getParams();
            HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
            HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
        }

        try {
            if (header != null && header.size() != 0) {
                Iterator<String> iterator = header.keySet().iterator();

                while(iterator.hasNext()) {
                    String key = (String)iterator.next();
                    post.setHeader(key, (String)header.get(key));
                }
            }

            StringEntity se = new StringEntity(json, ContentType.APPLICATION_JSON);
            se.setContentType("text/json;");
            post.setEntity(se);
            HttpResponse response = client.execute(post);
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                Header respHeader = resEntity.getContentEncoding();
                if (respHeader == null || !"gzip".equalsIgnoreCase(respHeader.getValue()) && !"x-gzip".equalsIgnoreCase(respHeader.getValue())) {
                    data = EntityUtils.toString(resEntity);
                } else {
                    GzipDecompressingEntity gzipEntity = new GzipDecompressingEntity(resEntity);
                    InputStream in = gzipEntity.getContent();
                    data = getHTMLContent(in);
                }
            }
        } catch (IOException var19) {
            logger.warn("消息发送至OA异常:", var19);
            JSONObject errObj = new JSONObject();
            errObj.put("operResult", "0");
            errObj.put("message", "消息发送至OA异常:" + var19);
            data = errObj.toJSONString();
//            throw var19;
        } catch (Exception e){
            logger.warn("消息发送至OA异常:", e);
            JSONObject errObj = new JSONObject();
            errObj.put("operResult", "0");
            errObj.put("message", "消息发送至OA异常:" + e);
            data = errObj.toJSONString();
        } finally {
            post.releaseConnection();
        }

        return data;
    }

    private static String getHTMLContent(InputStream in) {
        StringBuffer sb = new StringBuffer();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));

        try {
            String line = null;

            while((line = br.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException var12) {
            logger.error("getHTMLContent error", var12);
        } finally {
            try {
                br.close();
            } catch (IOException var11) {
                logger.error("getHTMLContent error", var11);
            }

        }

        return sb.toString();
    }

    private static HttpClient createHttpClient(int connectionTimeout, int readTimeout) {
        HttpClient client = new DefaultHttpClient();
        HttpParams httpParams = client.getParams();
        HttpConnectionParams.setConnectionTimeout(httpParams, connectionTimeout);
        HttpConnectionParams.setSoTimeout(httpParams, readTimeout);
        return client;
    }

    public static HttpClient wrapperHttpClient(int connectionTimeout, int readTimeout) {
        try {
            final X509TrustManager trustManager = new X509TrustManager() {
                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(final javax.security.cert.X509Certificate[] arg0, final String arg1) throws CertificateException {
                }

                public void checkServerTrusted(final javax.security.cert.X509Certificate[] arg0, final String arg1) throws CertificateException {
                }

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

                @Override
                public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws java.security.cert.CertificateException {
                }
            };
            SSLContext ctx = SSLContext.getInstance("TLS");
            ctx.init((KeyManager[])null, new TrustManager[]{trustManager}, (SecureRandom)null);
            SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(ctx, NoopHostnameVerifier.INSTANCE);
            RequestConfig requestConfig = RequestConfig.custom().setCookieSpec("standard-strict").setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(connectionTimeout).setSocketTimeout(readTimeout).setExpectContinueEnabled(Boolean.TRUE).setTargetPreferredAuthSchemes(Arrays.asList("NTLM", "Digest")).setProxyPreferredAuthSchemes(Arrays.asList("Basic")).build();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", socketFactory).build();
            PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            CloseableHttpClient closeableHttpClient = HttpClients.custom().setConnectionManager(connectionManager).setDefaultRequestConfig(requestConfig).build();
            return closeableHttpClient;
        } catch (Exception var9) {
            logger.error("包装无证书校验客户端失败:" + var9.getMessage());
            return null;
        }
    }
}
