package com.sifang.modules.customer.utils;

import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.util.UUID;

public class JavaDemo {

    static class miTM implements TrustManager,
            X509TrustManager {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return null;
        }

        public boolean isServerTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public boolean isClientTrusted(
                java.security.cert.X509Certificate[] certs) {
            return true;
        }

        public void checkServerTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }

        public void checkClientTrusted(
                java.security.cert.X509Certificate[] certs, String authType)
                throws java.security.cert.CertificateException {
            return;
        }
    }

    public static void main(String[] args) throws Exception {

       String url = "https://59.37.128.138:442/out/retail_leasing/oauth/token?client_id=Finance&client_secret=53e18ab1-67cc-475f-b54b-32c00f8b9bd6&grant_type=password&username=hty001&password=Password@123";
        String sslAddress = "D:\\Downloads\\证书访问测试环境demo\\Java\\client.p12";
        String sslPassword = "Yx12345678";
        String reqJson = new String();
       // String sslAddress = "D:\\Downloads\\证书访问测试环境demo\\Java\\client.p12";
        String resultData = "";

        KeyStore clientKeyStore = KeyStore.getInstance("PKCS12");
        clientKeyStore.load(new BufferedInputStream(new FileInputStream(sslAddress)), sslPassword.toCharArray());
//            此类充当基于密钥内容源的密钥管理器的工厂。每个密钥管理器管理特定类型的、由安全套接字所使用的密钥内容。密钥内容是基于 KeyStore 和/或提供者特定的源。
        KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        keyManagerFactory.init(clientKeyStore, sslPassword.toCharArray());

        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                System.out.println("Warning: URL Host: " + urlHostName + " vs. "
                        + session.getPeerHost());
                return true;
            }
        };

        TrustManager[] trustAllCerts = new TrustManager[1];
        TrustManager tm = new miTM();
        trustAllCerts[0] = tm;
        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sslContext
                .getSocketFactory());

        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        HttpsURLConnection connection = null;
        try {
            URL myURL = new URL(url);
            connection = (HttpsURLConnection) myURL.openConnection();

            connection.setSSLSocketFactory(sslContext.getSocketFactory());
            // 设置不验证服务器，返回true不验证，false为验证，默认为false；也可以根据arg0的值验证或不验证指定服务器；
            connection.setHostnameVerifier((m1, m2) -> true);

            connection.setRequestMethod("POST");
            //从服务器获取数据
            connection.setDoInput(true);
            //向服务器传输数据
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.connect();

            if (!reqJson.isEmpty()) {
                OutputStream outputStream = connection.getOutputStream();
                outputStream.write(reqJson.getBytes());
                outputStream.flush();
                outputStream.close();
            }

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(connection.getInputStream(), "utf-8"))) {
                StringBuilder results = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    results.append(line);
                }
                resultData = results.toString();
            }
            System.out.println(resultData);
        } catch (Exception e){
            throw e;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }

}