前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java代码忽略https证书:解决No subject alternative names present问题 HttpURLConnection https请求

Java代码忽略https证书:解决No subject alternative names present问题 HttpURLConnection https请求

作者头像
oktokeep
发布2024-10-09 10:50:35
1240
发布2024-10-09 10:50:35
举报
文章被收录于专栏:第三方工具

Java代码忽略https证书:解决No subject alternative names present问题

代码语言:javascript
复制
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * Java代码忽略https证书:解决No subject alternative names present问题
 */
public class HttpsUtils {
    private static final Logger logger = LoggerFactory.getLogger(HttpsUtils.class);


    public static String get(String hosturl,String params,String contentType) throws IOException, KeyManagementException, NoSuchAlgorithmException {
        HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        URL url = new URL(hosturl+"?"+params);
        logger.info("参数:"+hosturl+"?"+params);

        // 打开restful链接
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");// POST GET PUT DELETE
        conn.setRequestProperty("accept", "*/*");
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
        conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");

        // 设置访问提交模式,表单提交
//        conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
//        conn.setRequestProperty("Content-Type",contentType);
        conn.setConnectTimeout(130000);// 连接超时 单位毫秒
        conn.setReadTimeout(130000);// 读取超时 单位毫秒

        // 读取请求返回值
        byte bytes[] = new byte[1024];
        InputStream inStream = conn.getInputStream();
        inStream.read(bytes, 0, inStream.available());
        logger.info("返回结果:" + new String(bytes, "utf-8"));
        return new String(bytes, "utf-8");
    }

    /**
     *
     * @param hosturl
     * @param params
     * @param contentType  text/plain;charset=utf-8     application/json;charset=utf-8
     * @return
     * @throws IOException
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     */
    public static String post(String hosturl,String params,String contentType)  {
        StringBuffer result = new StringBuffer();
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        HttpURLConnection conn = null;
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
//        URL url = new URL(hosturl+"?"+params);
//        logger.info("参数:"+hosturl+"?"+params);

            URL url = new URL(hosturl);
            logger.info("参数url:" + hosturl +",params:"+ params);

            // 打开restful链接
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");// POST GET PUT DELETE
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");

            // 设置访问提交模式,表单提交
//        conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
//        conn.setRequestProperty("Content-Type",contentType);
            conn.setConnectTimeout(130000);// 连接超时 单位毫秒
            conn.setReadTimeout(130000);// 读取超时 单位毫秒
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //拼装参数
            if (null != params && !params.equals("")) {
                //设置参数
                os = conn.getOutputStream();
                //拼装参数
                os.write(params.getBytes("UTF-8"));
                logger.info("发送请求参数成功,params:"+params);
            }


            // 读取请求返回值,收不到返回??
//        byte bytes[] = new byte[1024];
//        InputStream inStream = conn.getInputStream();
//        inStream.read(bytes, 0, inStream.available());
//        logger.info("返回结果:" + new String(bytes, "utf-8"));
//        return new String(bytes, "utf-8");

            //读取响应
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }else{
                    logger.error("连接获取返回inputStream null");
                }
            }

            logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString());

        }catch (Exception e) {
            logger.error("post exception:",e);
        }finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            conn.disconnect();
        }
        return result.toString();
    }

    /**
     *
     * @param hosturl
     * @param params
     * @param contentType
     * @return
     * @throws IOException
     * @throws KeyManagementException
     * @throws NoSuchAlgorithmException
     */
    public static String postJson(String hosturl,String params,String contentType) {
        StringBuffer result = new StringBuffer();
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        HttpURLConnection conn = null;

        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HttpsUtils().new NullHostNameVerifier());
            SSLContext sc = SSLContext.getInstance("TLS");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
            URL url = new URL(hosturl);
            logger.info("参数url:" + hosturl + ",params=" + params);
            // 打开restful链接
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");// POST GET PUT DELETE
            // 设置访问提交模式,表单提交
//        conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
//        conn.setRequestProperty("Content-Type",contentType);
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setConnectTimeout(130000);// 连接超时 单位毫秒
            conn.setReadTimeout(130000);// 读取超时 单位毫秒
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            conn.setDoOutput(true);
            conn.setDoInput(true);

            //拼装参数
            if (null != params && !params.equals("")) {
                //设置参数
                os = conn.getOutputStream();
                //拼装参数
                os.write(params.getBytes("UTF-8"));
                logger.info("发送请求参数成功,params:"+params);
            }

            //读取响应 // 读取请求返回值,收不到返回??
//        if (conn.getResponseCode() == 200) {
            // 读取请求返回值
//            byte bytes[] = new byte[1024];
//            InputStream inStream = conn.getInputStream();
//            inStream.read(bytes, 0, inStream.available());
//            logger.info("返回结果:" + new String(bytes, "utf-8"));
//            return new String(bytes, "utf-8");
//        }
//        return null;

            //读取响应
            if (conn.getResponseCode() == 200) {
                is = conn.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }else{
                    logger.error("连接获取返回inputStream null");
                }
            }

            logger.info("responseCode:"+conn.getResponseCode()+"返回url:" + hosturl +",返回result:"+ result.toString());

        }catch (Exception e) {
            logger.error("postJson exception:",e);
        }finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            conn.disconnect();
        }
        return result.toString();
    }


    static TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    } };

    public class NullHostNameVerifier implements HostnameVerifier {
        /*
         * (non-Javadoc)
         *
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return true;
        }
    }

}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-03-29,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
SSL 证书
腾讯云 SSL 证书(SSL Certificates)为您提供 SSL 证书的申请、管理、部署等服务,为您提供一站式 HTTPS 解决方案。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档