package com.sy.coinage.core.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.config.RequestConfig.Builder;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;

import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

/**
 * -http请求工具类
 *
 * @author: lug 2022年5月12日
 */
@SuppressWarnings("all")
public class HttpClientUtil {

    /**
     * get:()
     *
     * @param url
     * @param params
     * @param headerParams
     * @return
     */
    public static String get(String url, List<NameValuePair> params, List<NameValuePair> headerParams) {
        CloseableHttpClient hc = HttpClientBuilder.create().build();
        String body = null;
        try {
            // Get请求
            HttpGet httpget = new HttpGet(url);
            // 设置参数
            if (params != null && params.size() > 0) {
                String str = EntityUtils.toString(new UrlEncodedFormEntity(params));
                httpget.setURI(new URI(httpget.getURI().toString() + "?" + str));
            }
            // 发送请求
            HttpResponse httpresponse = hc.execute(httpget);
            httpresponse.setHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8");
            if (headerParams != null) {
                for (NameValuePair param : headerParams) {
                    if (param != null && param.getName() != null && param.getValue() != null) {
                        httpresponse.setHeader(param.getName(), param.getValue());
                    }
                }
            }
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            body = EntityUtils.toString(entity);
            // 关闭流
            EntityUtils.consume(entity);
            // body = EntityUtils.toString(entity);
            // if (entity != null) {
            // entity.consumeContent();
            // entity.getContent().close();
            // }
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } finally {
            try {
                hc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * post:()
     *
     * @param url
     * @param sendBody
     * @return
     */
    public static String post(String url, String sendBody) {
        return post(url, sendBody, null);
    }

    /**
     * post:()
     *
     * @param url
     * @param sendBody
     * @param headerParams
     * @return
     */
    public static String post(String url, String sendBody, List<NameValuePair> headerParams) {
        CloseableHttpClient hc = HttpClientBuilder.create().build();
        // HttpvClient httpClient = new DefaultHttpClient();
        String body = null;
        try {
            // Post请求
            HttpPost post = new HttpPost(url);
            StringEntity se = new StringEntity(sendBody, "UTF-8");
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            post.setEntity(se);
            if (headerParams != null) {
                for (NameValuePair param : headerParams) {
                    if (param != null && param.getName() != null && param.getValue() != null) {
                        post.setHeader(param.getName(), param.getValue());
                    }
                }
            }
            // 发送请求
            HttpResponse httpresponse = hc.execute(post);
            if (httpresponse.getStatusLine().getStatusCode() != 200) {
                return null;
            }
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            // //得到实体输入流
            // InputStream inSm = entity.getContent();
            // Scanner inScn = new Scanner(inSm);
            // while(inScn.hasNextLine()){
            // System.out.println(inScn.nextLine());
            // }
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                hc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return body;
    }

    public static String postXML(String url, String sendBody) {
        return postXML(url, sendBody, null);
    }

    public static String postXML(String url, String sendBody, List<NameValuePair> headerParams) {
        CloseableHttpClient hc = HttpClientBuilder.create().build();
        String body = null;
        try {
            // Post请求
            HttpPost post = new HttpPost(url);
            StringEntity se = new StringEntity(sendBody, "UTF-8");
            // se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
            // "application/xml;charset=UTF-8"));
            post.setEntity(se);
            if (headerParams != null) {
                for (NameValuePair param : headerParams) {
                    if (param != null && param.getName() != null && param.getValue() != null) {
                        post.setHeader(param.getName(), param.getValue());
                    }
                }
            }
            // 发送请求
            HttpResponse httpresponse = hc.execute(post);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            // //得到实体输入流
            // InputStream inSm = entity.getContent();
            // Scanner inScn = new Scanner(inSm);
            // while(inScn.hasNextLine()){
            // System.out.println(inScn.nextLine());
            // }
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                hc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * put:()
     *
     * @param url
     * @param sendBody
     * @return
     */
    public static String put(String url, String sendBody) {
        return post(url, sendBody, null);
    }

    public static String put(String url, String sendBody, List<NameValuePair> headerParams) {
        CloseableHttpClient hc = HttpClientBuilder.create().build();
        String body = null;
        try {
            // Put请求
            HttpPut httpput = new HttpPut(url);
            StringEntity se = new StringEntity(sendBody, "UTF-8");
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            httpput.setEntity(se);
            if (headerParams != null) {
                for (NameValuePair param : headerParams) {
                    if (param != null && param.getName() != null && param.getValue() != null) {
                        httpput.setHeader(param.getName(), param.getValue());
                    }
                }
            }
            // 发送请求
            HttpResponse httpresponse = hc.execute(httpput);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            // //得到实体输入流
            // InputStream inSm = entity.getContent();
            // Scanner inScn = new Scanner(inSm);
            // while(inScn.hasNextLine()){
            // System.out.println(inScn.nextLine());
            // }
            body = EntityUtils.toString(entity);
            EntityUtils.consume(entity);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                hc.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return body;
    }

    /**
     * 创建 SSL连接
     *
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl) throws IOException {}

                @Override
                public void verify(String host, X509Certificate cert) throws SSLException {}

                @Override
                public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {}

            });
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (GeneralSecurityException e) {
            throw e;
        }
    }

    public static String postHttps(String url, String sendBody, List<NameValuePair> headerParams) {
        HttpClient client = null;
        HttpPost post = new HttpPost(url);
        String result = "";
        try {
            // HttpEntity entity = new StringEntity(sendBody, ContentType.create(mimeType, charset));
            // post.setEntity(entity);
            StringEntity se = new StringEntity(sendBody, "UTF-8");
            se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
            post.setEntity(se);
            if (headerParams != null) {
                for (NameValuePair param : headerParams) {
                    if (param != null && param.getName() != null && param.getValue() != null) {
                        post.setHeader(param.getName(), param.getValue());
                    }
                }
            }
            // 设置参数
            Builder customReqConf = RequestConfig.custom();
            post.setConfig(customReqConf.build());
            HttpResponse res;
            // 执行 Https 请求.
            client = createSSLInsecureClient();
            res = client.execute(post);
            result = IOUtils.toString(res.getEntity().getContent(), "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            post.releaseConnection();
            try {
                if (url.startsWith("https") && client != null && client instanceof CloseableHttpClient) {
                    ((CloseableHttpClient) client).close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String httpRequestPost(String requestUrl, String outputStr) {
        // 创建SSLContext
        StringBuffer buffer = null;
        try {
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestProperty("token", "AC11IEKPYIKRRK529RJT7VTZWPOD0");
            conn.setRequestProperty("transactionId", "1111");
            conn.setRequestProperty("version", "1");
            conn.setRequestProperty("deviceType", "1");
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            // 往服务器端写内容
            if (null != outputStr) {
                OutputStream os = conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

}
