package com.thinkgem.jeesite.modules.youka.utils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
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.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static java.lang.System.currentTimeMillis;

/***
 * httpUtil
 *
 * @author
 */

public class JFenHttpUtil {

    private static final org.slf4j.Logger log = LoggerFactory.getLogger(HttpUtil.class);

    private static PoolingHttpClientConnectionManager cm = null;

    private static RequestConfig defaultRequestConfig = null;

    static {
        try {
            //采用绕过验证的方式处理https请求
            SSLContext sslcontext = createIgnoreVerifySSL();
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                    .register("https", new SSLConnectionSocketFactory(sslcontext))
                    .register("http", new PlainConnectionSocketFactory())
                    .build();
            cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            cm.setMaxTotal(2000);
            cm.setDefaultMaxPerRoute(20);
            defaultRequestConfig = RequestConfig.custom()
                    .setSocketTimeout(30000)
                    .setConnectTimeout(30000)
                    .setConnectionRequestTimeout(30000)
                    .setStaleConnectionCheckEnabled(true)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static SSLContext createIgnoreVerifySSL() throws Exception {
        SSLContext sc = SSLContext.getInstance("SSLv3");

        // 实现一个X509TrustManager接口，用于绕过验证，不用修改里面的方法
        X509TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,
                    String paramString) throws CertificateException {
            }

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

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

        sc.init(null, new TrustManager[]{trustManager}, null);
        return sc;
    }

    public static String get(String url, String param) throws IOException {

        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;

        // 发送get请求
        try {
            // 用get方法发送http请求
            HttpGet get = new HttpGet(url + URLEncoder.encode(param, "UTF-8"));
            get.setHeader("User-Agent", "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Ubuntu Chromium/51.0.2704.79 Chrome/51.0.2704.79 Safari/537.36");
            System.out.println("执行get请求, uri: " + get.getURI());
            response = httpclient.execute(get);
            // response实体
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                String str = EntityUtils.toString(entity);
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == HttpStatus.SC_OK) {
                    // 成功
                    return str;
                } else {
                    return null;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("httpclient请求失败");
            return null;
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return null;
    }

    public static String post(String url, List<NameValuePair> nvps) throws Exception {

        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String str = "";
        try {

            httpPost = new HttpPost(url);

            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));

            response = httpclient.execute(httpPost);

            HttpEntity entity = response.getEntity();
            str = EntityUtils.toString(entity);
            log.debug("httpclient调用状态:" + response.getStatusLine());
            log.debug("httpclient调用结果{}", str);
            // return EntityUtils.toString(response.getEntity());
            return str;

        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }


    public static String post(String url, Map<String, Object> params) throws Exception {
        Long time = System.currentTimeMillis();
//        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();

        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        String str = "";
        try {
            httpPost = new HttpPost(url);
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                list.add(new BasicNameValuePair(key, "" + params.get(key)));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
                httpPost.setEntity(new UrlEncodedFormEntity(list, "UTF-8"));
            }
            response = httpclient.execute(httpPost);
            str = EntityUtils.toString(response.getEntity(), "UTF-8");
            log.info("请求耗时:{}ms", (System.currentTimeMillis() - time));
            return str;
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }

        }

    }


    public static String postRaw(String url, String json) throws Exception {

        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String str = "";
        try {

            httpPost = new HttpPost(url);
            StringEntity postingString = new StringEntity(json,"UTF-8");// json传递
            httpPost.setEntity(postingString);
            httpPost.setHeader("Content-type", "application/json");
            response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                str = EntityUtils.toString(entity,"UTF-8");
                log.debug("httpclient调用状态:" + response.getStatusLine());
                log.debug("httpclient调用结果{}", str);
                // return EntityUtils.toString(response.getEntity());
                return str;
            } finally {
                response.close();
            }

        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

    public static String get(String url) throws Exception {
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        HttpGet httpget = null;
        try {

            httpget = new HttpGet(url);
            String str = "";
            response = httpclient.execute(httpget);
            // 获取状态行
            HttpEntity entity = response.getEntity();
            str = EntityUtils.toString(entity);
            log.debug("httpclient调用状态:" + response.getStatusLine());
            log.debug("httpclient调用结果{}", str);
            return str;
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpget != null) {
                httpget.releaseConnection();
            }
        }

    }

    public static void main(String[] args) {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        try {
            for (int i = 0; i < 200; i++) {
                Long time = currentTimeMillis();
                get("https://www.baidu.com/website/index");
                System.out.println("耗时:" + ((currentTimeMillis() - time) / 1000) + "s");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static String formSubmit(String url, Map<String, Object> params) throws IOException {
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        CloseableHttpResponse response = null;
        HttpPost httpPost = null;
        String str = "";
        try {
            httpPost = new HttpPost(url);
            httpPost.setHeader("Accept", "Accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
            httpPost.setHeader("Accept-Charset", "GB2312,utf-8;q=0.7,*;q=0.7");
            httpPost.setHeader("Accept-Encoding", "gzip, deflate");
            httpPost.setHeader("Accept-Language", "zh-cn,zh;q=0.5");
            httpPost.setHeader("Connection", "keep-alive");
            httpPost.setHeader("Cookie", "__utma=226521935.73826752.1323672782.1325068020.1328770420.6;");
            httpPost.setHeader("Host", "localhost");
            httpPost.setHeader("refer", "");
            httpPost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; rv:6.0.2) Gecko/20100101 Firefox/6.0.2");

            httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
            //设置参数
            List<NameValuePair> list = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                list.add(new BasicNameValuePair(key, "" + params.get(key)));
            }
            if (list.size() > 0) {
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list);
                httpPost.setEntity(new UrlEncodedFormEntity(list, "utf-8"));
            }


            response = httpclient.execute(httpPost);
            str = EntityUtils.toString(response.getEntity(), "UTF-8");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return str;
    }

    public static String sendData(String url, String xml) throws Exception {
        Long time = System.currentTimeMillis();
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String str = "";
        try {

            httpPost = new HttpPost(url);
            StringEntity postingString = new StringEntity(xml, "UTF-8");// json传递
            httpPost.setEntity(postingString);
            response = httpclient.execute(httpPost);

            try {
                str = EntityUtils.toString(response.getEntity(), "UTF-8");
                log.debug("请求耗时:{}ms", (System.currentTimeMillis() - time));
                return str;
            } finally {
                response.close();
            }
        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }

    public static String post(String url, String json) throws Exception {
        CloseableHttpClient httpclient = HttpClients.custom().setConnectionManager(cm).build();
        HttpPost httpPost = null;
        CloseableHttpResponse response = null;
        String str = "";
        try {

            httpPost = new HttpPost(url);
            StringEntity postingString = new StringEntity(json,"UTF-8");// json传递
            httpPost.setEntity(postingString);
            httpPost.setHeader("Content-type", "application/json");
            response = httpclient.execute(httpPost);
            try {
                HttpEntity entity = response.getEntity();
                str = EntityUtils.toString(entity,"UTF-8");
                log.debug("httpclient调用状态:" + response.getStatusLine());
                log.debug("httpclient调用结果{}", str);
                // return EntityUtils.toString(response.getEntity());
                return str;
            } finally {
                response.close();
            }

        } finally {
            if (response != null) {
                response.close();
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
    }
}
