package com.JN.utils;


import org.apache.http.*;
import org.apache.http.client.ClientProtocolException;
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.client.methods.HttpUriRequest;
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.HttpClientBuilder;
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 javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @ClassName HttpHelper
 * @Description HTTP工具类
 * @Author JN
 * @Date 2024/1/11 14:29
 * @Version 1.0
 */
public class HttpHelper {

    // get 请求
    public static String httpGet(String url, Header[] headers) throws Exception {
        HttpUriRequest uriRequest = new HttpGet(url);
        if (null != headers)
            uriRequest.setHeaders(headers);
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            CloseableHttpResponse httpresponse = httpClient.execute(uriRequest);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            System.out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[] { url, e }));
        } catch (IOException e) {
            System.out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[] { url, e }));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }
        return null;
    }

    // post 请求
    public static String httpPost(String url, String params) throws Exception {
        HttpPost post = new HttpPost(url);
        post.addHeader("Content-Type", "application/json;charset=" + REQ_ENCODEING_UTF8);
        // 设置传输编码格式
        StringEntity stringEntity = new StringEntity(params, REQ_ENCODEING_UTF8);
        stringEntity.setContentEncoding(REQ_ENCODEING_UTF8);
        post.setEntity(stringEntity);
        HttpResponse httpresponse = null;
        CloseableHttpClient httpClient = null;
        try {
            httpClient = declareHttpClientSSL(url);
            httpresponse = httpClient.execute(post);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            System.out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[] { url, e }));
        } catch (IOException e) {
            System.out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[] { url, e }));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }
        return null;
    }

    /**
     * @title httpPost
     * @description 支持传入自己的head头的post请求
     * @author JIAL
     * @param: url
     * @param: params
     * @param: headers
     * @updateTime 2024/1/17 10:34
     * @return: java.lang.String
     */
    public static String httpPost(String url, Map<String, String> params, Map<String, String> headers) throws Exception {
        HttpPost post = new HttpPost(url);

        // Add custom headers
        if (headers != null && !headers.isEmpty()) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.addHeader(entry.getKey(), entry.getValue());
            }
        }

        // Set request body if params is not null
        if (params != null && !params.isEmpty()) {
            List<NameValuePair> formParams = new ArrayList<>();
            for (Map.Entry<String, String> entry : params.entrySet()) {
                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
            }
            UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formParams, Consts.UTF_8);
            post.setEntity(urlEncodedFormEntity);
        }

        HttpResponse httpresponse = null;
        CloseableHttpClient httpClient = null;

        try {
            httpClient = declareHttpClientSSL(url);
            httpresponse = httpClient.execute(post);
            HttpEntity httpEntity = httpresponse.getEntity();
            String result = EntityUtils.toString(httpEntity, REQ_ENCODEING_UTF8);
            return result;
        } catch (ClientProtocolException e) {
            System.out.println(String.format("http请求失败，uri{%s},exception{%s}", new Object[] { url, e }));
        } catch (IOException e) {
            System.out.println(String.format("IO Exception，uri{%s},exception{%s}", new Object[] { url, e }));
        } finally {
            if (null != httpClient)
                httpClient.close();
        }

        return null;
    }

    private static CloseableHttpClient declareHttpClientSSL(String url) {
        if (url.startsWith("https://")) {
            return sslClient();
        } else {
            return HttpClientBuilder.create().setConnectionManager(httpClientConnectionManager).build();
        }
    }

    /**
     * 设置SSL请求处理
     */
    private static CloseableHttpClient sslClient() {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {
                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {
                }
            };
            ctx.init(null, new TrustManager[] { tm }, null);
            SSLConnectionSocketFactory sslConnectionSocketFactory = SSLConnectionSocketFactory.getSocketFactory();
            return HttpClients.custom().setSSLSocketFactory(sslConnectionSocketFactory).build();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (KeyManagementException e) {
            throw new RuntimeException(e);
        }
    }

    // this is config
    private static final String REQ_ENCODEING_UTF8 = "utf-8";
    private static PoolingHttpClientConnectionManager httpClientConnectionManager;

    public HttpHelper() {
        httpClientConnectionManager = new PoolingHttpClientConnectionManager();
        httpClientConnectionManager.setMaxTotal(100);
        httpClientConnectionManager.setDefaultMaxPerRoute(20);
    }

    // get 请求
    public static String httpGet(String url) throws Exception {
        return httpGet(url, null);
    }

    /**
     * @title urlEncode
     * @description 将Map类型转换为请求参数param
     * @author JN
     * @param: data
     * @updateTime 2024/1/11 16:38
     * @return: java.lang.String
     */
    public static String urlEncode(Map<String, ?> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, ?> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String result = sb.toString();
        result = result.substring(0, result.lastIndexOf("&"));
        return result;
    }
}