0
点赞
收藏
分享

微信扫一扫

java 处理ssl验证

彭维盛 2022-03-30 阅读 85
javassl

处理ssl验证

/**
     * 
     * @param url
     * @param params "var1=var1&var2=var2"
     * @return
     * @throws Exception
     */
     String doPOST(String url, String params) throws Exception {
        String result = null;
        /**
         * 现在很多站点都是SSL对数据传输进行加密,这也让普通的HttpConnection无法正常的获取该页面的内容,
         * 发现可以为本地HttpsURLConnection配置一个“万能证书”,其原理是就是:
         * 重置HttpsURLConnection的DefaultHostnameVerifier,使其对任意站点进行验证时都返回true
         * 重置httpsURLConnection的DefaultSSLSocketFactory, 使其生成随机证书
         */
        try {
            // 重置HttpsURLConnection的DefaultHostnameVerifier,使其对任意站点进行验证时都返回true
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            // 创建随机证书生成工厂
            //SSLContext context = SSLContext.getInstance("TLS");
            SSLContext context = SSLContext.getInstance("TLSv1.2");
            context.init(null, new X509TrustManager[]{new X509TrustManager() {
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                }

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

                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, new SecureRandom());

            // 重置httpsURLConnection的DefaultSSLSocketFactory, 使其生成随机证书
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());

            //业务代码
            BufferedReader reader = null;
            StringBuffer sbf = new StringBuffer();
            URL httpUrl = new URL(url);
            HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setDoOutput(true);
            connection.getOutputStream().write(params.getBytes("UTF-8"));
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = null;
            while ((strRead = reader.readLine()) != null) {
                sbf.append(strRead);
                sbf.append("\r\n");
            }
            reader.close();
            result = sbf.toString();

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return result;

    }
    
举报

相关推荐

0 条评论