package com.qmth.teachcloud.cas.util.supwisdom.utils;

import com.qmth.teachcloud.cas.util.supwisdom.Constants;
import com.qmth.teachcloud.exchange.common.contant.SystemConstant;

import javax.net.ssl.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public abstract class HttpRequestUtils {

    public static String doGet(String urlStr) throws IOException {
        URL url = new URL(urlStr);
        InputStream in = null;
        HttpURLConnection conn = null;
        try {
            trustEveryone();
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(Constants.CONNECT_TIMEOUT);
            conn.connect();
            in = conn.getInputStream();
            return IOUtils.toString(in, SystemConstant.CHARSET);
        } finally {
            IOUtils.close(conn);
            IOUtils.closeQuietly(in);
        }
    }

    public static void trustEveryone() {

        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });

            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
