package com.mosty.common.core.util.http;

import org.apache.commons.lang3.StringUtils;

import javax.net.ssl.*;
import javax.servlet.http.HttpServletRequest;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Map;

public class HttpsPostUtil {
    //添加主机名验证程序类，设置不验证主机
    private final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };

    //添加信任主机
    private static void trustAllHosts() {
        // 创建不验证证书链的信任管理器 这里使用的是x509证书
        TrustManager[] trustAllCerts = new TrustManager[]{new MyX509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return new java.security.cert.X509Certificate[]{};
            }

            public void checkClientTrusted(X509Certificate[] chain, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] chain, String authType) {
            }
        }};
        // 安装所有信任的信任管理器
        try {
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            //HttpsURLConnection通过SSLSocket来建立与HTTPS的安全连接，SSLSocket对象是由SSLSocketFactory生成的。
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *  发送post 数据
     * @param urls
     * @return
     */
    public static String heart(String urls, String param, String contentType, String method) {
        StringBuffer sb=new StringBuffer();
        DataOutputStream out = null;
        BufferedReader responseReader = null;
        InputStream in1 = null;
        try {
            trustAllHosts();
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置传递方式
            conn.setRequestMethod(method);
            //System.out.println(conn.getRequestMethod());
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
//            byte[] data = (param).getBytes();
//            // 设置文件长度
//            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", contentType);
            conn.setRequestProperty("Authorization", param);
            // 开始连接请求
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            out.writeBytes(param);
            out.flush();

            //System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while((readLine=responseReader.readLine()) != null){
                    sb.append(readLine).append("\n");
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch(Exception e) {}
            try {
                out.close();
            } catch(Exception e) {}
        }

        return sb.toString();

    }
    
    /**
     *  发送post 数据
     * @param urls
     * @return
     */
    public static String sendPost(String urls, String param, String contentType, String method, Map<String, String> headerOptions) {
        StringBuffer sb=new StringBuffer();
        DataOutputStream out = null;
        BufferedReader responseReader = null;
        InputStream in1 = null;
        try {
            trustAllHosts();
            // 创建url资源
            URL url = new URL(urls);
            // 建立http连接
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.setHostnameVerifier(DO_NOT_VERIFY);
            // 设置不用缓存
            conn.setUseCaches(false);
            // 设置允许输出
            conn.setDoOutput(true);
            // 设置允许输入
            conn.setDoInput(true);
            // 设置传递方式
            conn.setRequestMethod(method);
            //System.out.println(conn.getRequestMethod());
            // 设置维持长连接
            conn.setRequestProperty("Connection", "Keep-Alive");
            // 设置文件字符集:
            conn.setRequestProperty("Charset", "UTF-8");
            // 转换为字节数组
//            byte[] data = (param).getBytes();
//            // 设置文件长度
//            conn.setRequestProperty("Content-Length", String.valueOf(data.length));
            // 设置文件类型:
            conn.setRequestProperty("Content-Type", contentType);
            if (headerOptions != null && headerOptions.size() > 0) {
                for (String key : headerOptions.keySet()) {
                    conn.setRequestProperty(key, headerOptions.get(key));
                }
            }
            // 开始连接请求
            conn.connect();
            out = new DataOutputStream(conn.getOutputStream());
            // 写入请求的字符串
            if(StringUtils.isNotBlank(param)) {
                out.writeBytes(param);
            }
            out.flush();

            //System.out.println(conn.getResponseCode());

            // 请求返回的状态
            if (HttpURLConnection.HTTP_OK == conn.getResponseCode()) {
                System.out.println("连接成功");
                // 请求返回的数据
                in1 = conn.getInputStream();
                String readLine;
                responseReader = new BufferedReader(new InputStreamReader(in1));
                while((readLine=responseReader.readLine()) != null){
                    sb.append(readLine).append("\n");
                }
            } else {
                System.out.println("error++");
            }
        } catch (Exception e) {

        } finally {
            try {
                if (null != responseReader)
                    responseReader.close();
                if (null != in1)
                    in1.close();
            } catch(Exception e) {}
            try {
                out.close();
            } catch(Exception e) {}
        }
        return sb.toString();
    }

    /**
     * map转url参数
     */
    public static String map2Url(Map<String, String> paramToMap) {
        if (null == paramToMap || paramToMap.isEmpty()) {
            return null;
        }
        StringBuffer url  = new StringBuffer();
        boolean      isfist = true;
        for (Map.Entry<String, String> entry : paramToMap.entrySet()) {
            if (isfist) {
                isfist = false;
            } else {
                url.append("&");
            }
            url.append(entry.getKey()).append("=");
            String value = entry.getValue();
            if (!StringUtils.isEmpty(value)) {
                url.append(value);
            }
        }
        return url.toString();
    }
    
    public static void main(String[] args) {
//        System.out.println("123");
//        Map<String, String> params = new HashMap<String, String>();
//        params.put("client_id", "xx.cn");
//        params.put("client_secret", "UY83SNFJWLU32NJSLJIK");
//        params.put("code", "40ce7f41d6562e47dbdc33593ddce1b46444cdb93514b3aaced7be90eb51a16f");
//        params.put("grant_type", "authorization_code");
//        params.put("redirect_uri", "xxn/index.jsp");
        //要发送的POST请求url?Key=Value&amp;Key2=Value2&amp;Key3=Value3的形式
        //application/json;charset=UTF-8  application/x-www-form-urlencoded;charset=UTF-8
//        String sb = sendPost("https://id.pdedu.sh.cn/connect/token",map2Url(params),"application/json;charset=UTF-8",
//                "POST");
        //System.out.println(sb);
        String token = "NzdlZGU2MzctMWUxNS00YTg0LWFhZTktNDg0NGM2Yzk1YjhlLDssO3sibWVudXMiOltdLCJwZXJtaXNzaW9uIjp7InJlc291cmNlcyI6WyIxMDAwMDAyIiwiMTAwMDAwMSIsIjEwMDAwMDQiLCIxMDAwMDAzIiwiNzA0MmU3MTAtODYxNS00MjM2LWFkNTMtYWQxMjEwZGJmYzViIl19LCJ1c2VyIjp7InVzZXJJZCI6Ijc3ZWRlNjM3LTFlMTUtNGE4NC1hYWU5LTQ4NDRjNmM5NWI4ZSIsInVzZXJuYW1lIjoiemhqbXhmIiwic3RhdHVzIjoiMDEiLCJpZE51bSI6IjUxMzEyNzE5OTQwMjI1MTAxMyIsIm5pY2tOYW1lIjoi5pm65oWn6KGX6Z2i5beh6Ziy5rK75a6J566h5o6nIiwiaXBBZGRyZXNzIjoiMjIzLjg1LjIwMy4xNDUiLCJ1c2VySW1nIjpbXSwibG9naW5UaW1lIjoiMjAyMi0wOC0xNFQxNTozMzoxMi4yNzMiLCJ1c2VyVHlwZXMiOlt7InVzZXJUeXBlSWQiOiJlNzMyYjIyZC01YWE5LTQyOGYtODY2NS1hYjNkYzAzMDFmYjgiLCJ0eXBlQ29kZSI6IkpNWEYiLCJ0eXBlTmFtZSI6Iuihl+mdouW3oemYsiIsInh0cHp4eGJJZCI6IjAwOGM3MTI0LWU0ZTYtNDI2Zi1hODE3LWE0OTc3MWU1MGQ4MCJ9XSwianVyaXNkaWN0aW9ucyI6W3siY3JlYXRlQnkiOiJmNmIyNTEyMy01ZDk2LTQ0M2YtODU5OC0xMzc1ZDE3MTgxZTciLCJjcmVhdGVUaW1lIjoiMjAyMi0wNy0yNlQxNDo0OTowNyIsImxhc3RNb2RpZmllZEJ5IjoiZjZiMjUxMjMtNWQ5Ni00NDNmLTg1OTgtMTM3NWQxNzE4MWU3IiwibGFzdE1vZGlmaWVkVGltZSI6IjIwMjItMDctMjZUMTQ6NTI6NTYiLCJqdXJpc2RpY3Rpb25JZCI6ImJmOWE2NmE3LWRiYjYtNDljMi1hMGUyLWY2ZmY1NzJjNTBmOSIsImp1cmlzZGljdGlvbkNvZGUiOiIxMTExMTEiLCJqdXJpc2RpY3Rpb25OYW1lIjoi5LuB5a+/5Y6/5YWs5a6J5bGAIiwicGFyZW50Ijp7Imp1cmlzZGljdGlvbklkIjoiMCJ9LCJqdXJpc0Z1bGxDb2RlIjoiMDEwMDAwLjExMTExMS4iLCJqdXJpc1NpbXBsZUNvZGUiOiIxMTExMTEifV19fSw7LDsxNjYxMDExMjAwMDAw.b3770a53935980c9f413724f25541590";
        token =  token.replace(" ","");
        token = token.replace("\\s*|\r|\n|\t","");
        Map<String, String> params = new HashMap<String, String>();
        params.put("Auth-Token", token);
        params.put("System-Id", "XLFK_ZHJMXFZAGK");
        String sb = sendPost("https://82.157.32.48:28080/api/user-auth", null,"application/json;charset=UTF-8",
                "POST", params);
        System.out.println(sb);
        
        
    }
   

    
}