java忽略证书验证(兼容http,https)

这篇具有很好参考价值的文章主要介绍了java忽略证书验证(兼容http,https)。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

概述

日常上传、下载文件时可能有不需要验证证书的场景,比如证书过期、不正确之类的也可以正常的上传下载文件。
Java中使用https协议时,是通过X.509证书进行校验的。
首先我们先了解下什么是X.509证书。

什么是X.509证书

X.509是公钥基础设施(PKI:Public Key Infrastructure)的标准格式,其实就是一种证书的标准格式,规定证书是什么样的。
X.509证书就是基于国际电线联盟(ITU)制定的X.509标准的数字证书。
X.509证书主要用于识别互联网通信和计算机网络中的身份,保护数据传输安全。X.509证书无处不在,比如我们每天使用的网站、移动应用程序、电子文档以及连接的设备等都有它的身影。

X.509证书的结构优势在于它是由公钥和私钥组成的密钥对而构建的。公钥和私钥能够用于加密和解密信息,验证发送者的身份和确保信息本身的安全性。基于X.509的PKI最常见的用例是使用SSL证书让网站与用户之间实现HTTPS安全浏览。X.509协议统一也使用于应用程序安全的代码签名、数字签名和其他重要的互联网协议。

证书校验引发的问题

javax.net.ssl.SSLException: hostname in certificate didn’t match

java忽略ssl证书,Web服务器,JAVA,安全,https,ssl,http
含义就是说现在程序运行的域名,与请求的证书不一致,不匹配导致的。那么解决方案必定是把证书忽略了,也就是不验证证书的情况下请求上游信息了。

java HttpsURLConnection忽略证书

HttpURLConnection是java的标准类,没有做封装,用起来比较原始,HttpURLConnection通常可以访问http/https协议,但是如果想忽略证书校验的话,需要使用HttpsURLConnection访问url,同时HttpsURLConnection只能访问https的协议。如果使用java原生的标准类访问url,对于Https的连接可以根据协议类型判断到底是使用HttpURLConnection还是HttpsURLConnection。
下面是HttpURLConnection和HttpURLConnection忽略证书访问的示例。

import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
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;

/**
 * @Description : java原生客户端忽略证书
 * @Version : V1.0.0
 * @Date : 2023/1/3 11:38
 */
public class JavaHttpUtil {

    /**
     * 发送https请求
     *
     * @param url           url
     * @param requestMethod 请求方式
     * @param param         请求参数
     * @return 返回值
     */
    public String sendHttpsRequest(String url, String requestMethod, String param) {
        StringBuilder result = new StringBuilder();
        try {
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                        }

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

                        @Override
                        public X509Certificate[] getAcceptedIssuers() {
                            return new X509Certificate[0];
                        }
                    }
            }, new SecureRandom());
            URL console = new URL(url);
            HttpsURLConnection conn = (HttpsURLConnection) console.openConnection();
            // GET/POST
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != param) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(param.getBytes("UTF-8"));
                outputStream.close();
            }

            // 设置证书忽略相关操作
            conn.setSSLSocketFactory(sc.getSocketFactory());
            conn.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !ret.trim().equals("")) {
                    result.append(new String(ret.getBytes("utf-8"), "utf-8"));
                }
            }
            conn.disconnect();
            br.close();
        } catch (NoSuchAlgorithmException | KeyManagementException | MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return result.toString();
    }

    // http协议访问方法
    public String sendHttpRequest(String url, String requestMethod, String param) {
        StringBuilder result = new StringBuilder();
        try {
            URL console = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) console.openConnection();
            // GET/POST
            conn.setRequestMethod(requestMethod);
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setDoOutput(true);
            conn.setDoInput(true);
            if (null != param) {
                OutputStream outputStream = conn.getOutputStream();
                // 注意编码格式
                outputStream.write(param.getBytes("UTF-8"));
                outputStream.close();
            }

            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String ret = "";
            while ((ret = br.readLine()) != null) {
                if (ret != null && !ret.trim().equals("")) {
                    result.append(new String(ret.getBytes("utf-8"), "utf-8"));
                }
            }
            conn.disconnect();
            br.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
        return result.toString();
    }

    public static void main(String[] args) {
        final JavaHttpUtil javaHttpUtil = new JavaHttpUtil();
        JSONObject js = new JSONObject();
        js.put("user", "xioamin");
        js.put("ip", "127.0.0.1");
        final String result = javaHttpUtil.sendHttpRequest("https://abc.test:5808/getToken", "POST", js.toString());
        System.out.println(result);

        final String get = javaHttpUtil.sendHttpsRequest("https://www.baidu.com/", "GET", null);
        System.out.println(get);
    }
}

org.apache.httpcomponents httpclient客户端忽略证书方法

HttpClient和httpurlconnection介绍

HttpClient是Apache开源组织提供的一个Http客户端,HttpClient封装了Session、Cookie等细节问题的处理。简单来说,HttpClient就是一个增强版的HttpURLConnection,HttpURLConnection可以做的事情 HttpClient全部可以做;HttpURLConnection没有提供的有些功能,HttpClient也提供了,但它只是关注于如何发送请求、接收响应,以及管理HTTP连接。

忽略证书示例

package com.practice.httputils.trustallcerts;


import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.config.SocketConfig;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.client.StandardHttpRequestRetryHandler;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Objects;

/**
 * @Description : httpComponents httpclient工具
 * @Version : V1.0.0
 * @Date : 2023/1/3 17:46
 */
public class HttpClientUtil {

    /**
     * 忽视所有证书验证-使用org.apache.httpcomponents 4.5版本
     *
     * @return
     */
    public static CloseableHttpClient trustAllCertsHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            // 忽略证书校验
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        }).build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[]{"TLSv1.2"}, null, NoopHostnameVerifier.INSTANCE);
        final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .register("https", sslConnectionSocketFactory).build();
        // 5秒超时
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(5000)
                .setSocketTimeout(10000).setConnectTimeout(10000).build();
        SocketConfig socketConfig = SocketConfig.custom().setSoTimeout(5000).build();
        PoolingHttpClientConnectionManager cm =
                new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        cm.setMaxTotal(300);
        // 单路由最大并发数
        cm.setDefaultMaxPerRoute(30);
        return HttpClients.custom()
                .setDefaultRequestConfig(requestConfig)
                .setRetryHandler(new StandardHttpRequestRetryHandler())
                .setDefaultSocketConfig(socketConfig).setConnectionManager(cm).build();
    }

    private static String sendPostHttpRequestWithTimeOut(String reqURL, String param, Map<String, String> headerMap, int readTimeout) throws HttpException {
        String result = "-1";
        HttpPost httpPost = new HttpPost(reqURL);
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json; charset=" + "UTF-8");
        CloseableHttpResponse response = null;
        try {
            if (param != null) {
                StringEntity entity = new StringEntity(param, "UTF-8");
                httpPost.setEntity(entity);
                if (!Objects.isNull(headerMap) && headerMap.size() != 0) {
                    for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                        httpPost.addHeader(entry.getKey(), entry.getValue());
                    }
                }
            }
            RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(3000).setConnectTimeout(4000)
                    .setSocketTimeout(readTimeout).build();
            httpPost.setConfig(requestConfig);
            response = trustAllCertsHttpClient().execute(httpPost, HttpClientContext.create());
            HttpEntity entity = response.getEntity();
            if (null != entity) {
                result = EntityUtils.toString(entity, ContentType.getOrDefault(entity).getCharset());
                EntityUtils.consume(entity);
            }
        } catch (Exception e) {
            throw new HttpException("请求通信[" + reqURL + "]时读取超时,堆栈轨迹如下:", e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (httpPost != null) {
                httpPost.releaseConnection();
            }
        }
        return result;
    }

    public static void main(String[] args) throws HttpException {
        JSONObject js = new JSONObject();
        js.put("user", "aaa");
        js.put("ip", "127.0.0.1");
        final String result = sendPostHttpRequestWithTimeOut("http://aaatest:5015/getToken", js.toString(), null, 3000);
        System.out.println(result);

        final String get = sendPostHttpRequestWithTimeOut("https://www.baidu.com/", null, null, 1000);
        System.out.println(get);
    }
}

参考

什么是X.509证书?X.509证书工作原理及应用?
java忽略证书验证(兼容http,https)进行get/post请求–使用(org.apache.httpcomponents httpclient客户端)
httpurlconnection 访问https
java忽略证书验证(兼容http,https)进行get/post请求–使用(org.apache.httpcomponents httpclient客户端)文章来源地址https://www.toymoban.com/news/detail-787559.html

到了这里,关于java忽略证书验证(兼容http,https)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java get/post的https请求忽略ssl证书认证

    unable to find valid certification path to requested target 工具类 使用方法

    2024年02月11日
    浏览(40)
  • HTTPS请求忽略SSL证书

    现场环境: 后端服务部署在docker内,远程调用https接口,线上报错: unable to find valid certification path to requested target 解决方案: 设置SSLSocketFactory忽略证书校验 实现案例: 使用的cn.hutool.http.HttpRequest工具类请求的数据,支持设置头部、表单、body、超时时间等关键信息 工具类 SSL

    2024年02月11日
    浏览(43)
  • RestTemplate HTTPS请求忽略SSL证书

    使用RestTemplate发送HTTPS请求的时候,出现了这样的一个问题: RestTemplate 默认不支持https协议 解决方案:         第一种是忽略认证         第二种是导入证书,比较复杂(比第一种安全)  这里说一下第一种解决方案,忽略认证 版本:Spring Boot2.x RestTemplateConfig 测试代

    2024年02月10日
    浏览(41)
  • 阿里云申请免费SSL证书的两种验证方式及配置服务器Tomcat升级HTTPS协议

    通用教程,其他服务商的免费 SSL 证书也差不多是这个流程。(至少腾讯云的操作步骤和本文是一致,嘻嘻!) 首先在阿里云上创建并申请 SSL 证书,之后选择 DNS 验证的方式,一种是手动配置解析地址进行验证,另一种是在服务器上放置一个验证文件进行验证。 手动 DNS 验证

    2024年02月10日
    浏览(39)
  • 请求第三方Https地址忽略SSL证书校验

    说明:个人使用记录 需要在请求之前忽略ssl协议,这里是直接使用静态方法初始化时就执行了 也需要在请求接口之前忽略SSL

    2024年04月10日
    浏览(35)
  • Tomcat配置https,JAVA生成ssl证书,http和https双向配置

    1、java生成ssl证书 首先要确认环境是否安装JDK;必须安装JDK才能生成SSL证书 1.1、服务器生成证书 服务器生成证书: 使用keytool为Tomcat生成证书,假定目标机器的域名是“127.0.0.1”,keystore文件存放在“D:omcat.keystore”,口令为“123456”,validity为证书有效时间当前为90天  生成命

    2024年02月01日
    浏览(33)
  • Openfeign和okHttp的https请求忽略ssl证书认证

    在通过feign和okhttp请求外部接口时,出现了以下问题: Servlet.service() for servlet [dispatcherServlet] in context with path [/xxxx] threw exception [Request processing failed; nested exception is feign.RetryableException: java.security.cert.CertificateException: No subject alternative DNS name matching www.xx.xx.cn found. executing GET htt

    2024年02月07日
    浏览(37)
  • springboot集成Elasticsearch7.16,使用https方式连接并忽略SSL证书

    千万万苦利用科学上网找到了,记录一下

    2024年02月09日
    浏览(38)
  • SpringBoot + Vue2项目打包部署到服务器后,使用Nginx配置SSL证书,配置访问HTTP协议转HTTPS协议

    配置nginx.conf文件,这个文件一般在/etc/nginx/...中,由于每个人的体质不一样,也有可能在别的路径里,自己找找... 证书存放位置,可自定义存放位置 两个文件 后端配置 把.pfx拷贝到resource下,然后配置一下yml

    2024年02月02日
    浏览(51)
  • 【Java开发】Spring Cloud 11:Gateway 配置 ssl 证书(https、http、域名访问)

    最近研究给微服务项目配置 ssl 证书,如此才可以对接微信小程序(需要使用 https 请求)。传统单体项目来说,首先往项目中添加证书文件,然后在配置文件中配置 ssl 证书路径、密码等相关信息;那么微服务这么多项目,总不能一个个配置 ssl 证书,最后发现可以直接通过网

    2024年02月08日
    浏览(53)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包