国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

java忽略證書驗(yàn)證(兼容http,https)

這篇具有很好參考價(jià)值的文章主要介紹了java忽略證書驗(yàn)證(兼容http,https)。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

概述

日常上傳、下載文件時(shí)可能有不需要驗(yàn)證證書的場(chǎng)景,比如證書過期、不正確之類的也可以正常的上傳下載文件。
Java中使用https協(xié)議時(shí),是通過X.509證書進(jìn)行校驗(yàn)的。
首先我們先了解下什么是X.509證書。

什么是X.509證書

X.509是公鑰基礎(chǔ)設(shè)施(PKI:Public Key Infrastructure)的標(biāo)準(zhǔn)格式,其實(shí)就是一種證書的標(biāo)準(zhǔn)格式,規(guī)定證書是什么樣的。
X.509證書就是基于國(guó)際電線聯(lián)盟(ITU)制定的X.509標(biāo)準(zhǔn)的數(shù)字證書。
X.509證書主要用于識(shí)別互聯(lián)網(wǎng)通信和計(jì)算機(jī)網(wǎng)絡(luò)中的身份,保護(hù)數(shù)據(jù)傳輸安全。X.509證書無處不在,比如我們每天使用的網(wǎng)站、移動(dòng)應(yīng)用程序、電子文檔以及連接的設(shè)備等都有它的身影。

X.509證書的結(jié)構(gòu)優(yōu)勢(shì)在于它是由公鑰和私鑰組成的密鑰對(duì)而構(gòu)建的。公鑰和私鑰能夠用于加密和解密信息,驗(yàn)證發(fā)送者的身份和確保信息本身的安全性?;赬.509的PKI最常見的用例是使用SSL證書讓網(wǎng)站與用戶之間實(shí)現(xiàn)HTTPS安全瀏覽。X.509協(xié)議統(tǒng)一也使用于應(yīng)用程序安全的代碼簽名、數(shù)字簽名和其他重要的互聯(lián)網(wǎng)協(xié)議。

證書校驗(yàn)引發(fā)的問題

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

java忽略ssl證書,Web服務(wù)器,JAVA,安全,https,ssl,http
含義就是說現(xiàn)在程序運(yùn)行的域名,與請(qǐng)求的證書不一致,不匹配導(dǎo)致的。那么解決方案必定是把證書忽略了,也就是不驗(yàn)證證書的情況下請(qǐng)求上游信息了。

java HttpsURLConnection忽略證書

HttpURLConnection是java的標(biāo)準(zhǔn)類,沒有做封裝,用起來比較原始,HttpURLConnection通??梢栽L問http/https協(xié)議,但是如果想忽略證書校驗(yàn)的話,需要使用HttpsURLConnection訪問url,同時(shí)HttpsURLConnection只能訪問https的協(xié)議。如果使用java原生的標(biāo)準(zhǔn)類訪問url,對(duì)于Https的連接可以根據(jù)協(xié)議類型判斷到底是使用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 {

    /**
     * 發(fā)送https請(qǐng)求
     *
     * @param url           url
     * @param requestMethod 請(qǐng)求方式
     * @param param         請(qǐng)求參數(shù)
     * @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();
            }

            // 設(shè)置證書忽略相關(guān)操作
            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協(xié)議訪問方法
    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開源組織提供的一個(gè)Http客戶端,HttpClient封裝了Session、Cookie等細(xì)節(jié)問題的處理。簡(jiǎn)單來說,HttpClient就是一個(gè)增強(qiáng)版的HttpURLConnection,HttpURLConnection可以做的事情 HttpClient全部可以做;HttpURLConnection沒有提供的有些功能,HttpClient也提供了,但它只是關(guān)注于如何發(fā)送請(qǐng)求、接收響應(yīng),以及管理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 {

    /**
     * 忽視所有證書驗(yàn)證-使用org.apache.httpcomponents 4.5版本
     *
     * @return
     */
    public static CloseableHttpClient trustAllCertsHttpClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() {
            // 忽略證書校驗(yàn)
            @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秒超時(shí)
        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);
        // 單路由最大并發(fā)數(shù)
        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("請(qǐng)求通信[" + reqURL + "]時(shí)讀取超時(shí),堆棧軌跡如下:", 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證書工作原理及應(yīng)用?
java忽略證書驗(yàn)證(兼容http,https)進(jìn)行g(shù)et/post請(qǐng)求–使用(org.apache.httpcomponents httpclient客戶端)
httpurlconnection 訪問https
java忽略證書驗(yàn)證(兼容http,https)進(jìn)行g(shù)et/post請(qǐng)求–使用(org.apache.httpcomponents httpclient客戶端)文章來源地址http://www.zghlxwxcb.cn/news/detail-787559.html

到了這里,關(guān)于java忽略證書驗(yàn)證(兼容http,https)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • Java get/post的https請(qǐng)求忽略ssl證書認(rèn)證

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

    2024年02月11日
    瀏覽(24)
  • HTTPS請(qǐng)求忽略SSL證書

    現(xiàn)場(chǎng)環(huán)境: 后端服務(wù)部署在docker內(nèi),遠(yuǎn)程調(diào)用https接口,線上報(bào)錯(cuò): unable to find valid certification path to requested target 解決方案: 設(shè)置SSLSocketFactory忽略證書校驗(yàn) 實(shí)現(xiàn)案例: 使用的cn.hutool.http.HttpRequest工具類請(qǐng)求的數(shù)據(jù),支持設(shè)置頭部、表單、body、超時(shí)時(shí)間等關(guān)鍵信息 工具類 SSL

    2024年02月11日
    瀏覽(22)
  • RestTemplate HTTPS請(qǐng)求忽略SSL證書

    使用RestTemplate發(fā)送HTTPS請(qǐng)求的時(shí)候,出現(xiàn)了這樣的一個(gè)問題: RestTemplate 默認(rèn)不支持https協(xié)議 解決方案: ????????第一種是忽略認(rèn)證 ????????第二種是導(dǎo)入證書,比較復(fù)雜(比第一種安全)? 這里說一下第一種解決方案,忽略認(rèn)證 版本:Spring Boot2.x RestTemplateConfig 測(cè)試代

    2024年02月10日
    瀏覽(25)
  • 阿里云申請(qǐng)免費(fèi)SSL證書的兩種驗(yàn)證方式及配置服務(wù)器Tomcat升級(jí)HTTPS協(xié)議

    阿里云申請(qǐng)免費(fèi)SSL證書的兩種驗(yàn)證方式及配置服務(wù)器Tomcat升級(jí)HTTPS協(xié)議

    通用教程,其他服務(wù)商的免費(fèi) SSL 證書也差不多是這個(gè)流程。(至少騰訊云的操作步驟和本文是一致,嘻嘻?。?首先在阿里云上創(chuàng)建并申請(qǐng) SSL 證書,之后選擇 DNS 驗(yàn)證的方式,一種是手動(dòng)配置解析地址進(jìn)行驗(yàn)證,另一種是在服務(wù)器上放置一個(gè)驗(yàn)證文件進(jìn)行驗(yàn)證。 手動(dòng) DNS 驗(yàn)證

    2024年02月10日
    瀏覽(372)
  • 請(qǐng)求第三方Https地址忽略SSL證書校驗(yàn)

    說明:個(gè)人使用記錄 需要在請(qǐng)求之前忽略ssl協(xié)議,這里是直接使用靜態(tài)方法初始化時(shí)就執(zhí)行了 也需要在請(qǐng)求接口之前忽略SSL

    2024年04月10日
    瀏覽(27)
  • Tomcat配置https,JAVA生成ssl證書,http和https雙向配置

    Tomcat配置https,JAVA生成ssl證書,http和https雙向配置

    1、java生成ssl證書 首先要確認(rèn)環(huán)境是否安裝JDK;必須安裝JDK才能生成SSL證書 1.1、服務(wù)器生成證書 服務(wù)器生成證書: 使用keytool為Tomcat生成證書,假定目標(biāo)機(jī)器的域名是“127.0.0.1”,keystore文件存放在“D:omcat.keystore”,口令為“123456”,validity為證書有效時(shí)間當(dāng)前為90天 ?生成命

    2024年02月01日
    瀏覽(24)
  • Openfeign和okHttp的https請(qǐng)求忽略ssl證書認(rèn)證

    在通過feign和okhttp請(qǐng)求外部接口時(shí),出現(xiàn)了以下問題: 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日
    瀏覽(21)
  • springboot集成Elasticsearch7.16,使用https方式連接并忽略SSL證書

    千萬萬苦利用科學(xué)上網(wǎng)找到了,記錄一下

    2024年02月09日
    瀏覽(25)
  • SpringBoot + Vue2項(xiàng)目打包部署到服務(wù)器后,使用Nginx配置SSL證書,配置訪問HTTP協(xié)議轉(zhuǎn)HTTPS協(xié)議

    SpringBoot + Vue2項(xiàng)目打包部署到服務(wù)器后,使用Nginx配置SSL證書,配置訪問HTTP協(xié)議轉(zhuǎn)HTTPS協(xié)議

    配置nginx.conf文件,這個(gè)文件一般在/etc/nginx/...中,由于每個(gè)人的體質(zhì)不一樣,也有可能在別的路徑里,自己找找... 證書存放位置,可自定義存放位置 兩個(gè)文件 后端配置 把.pfx拷貝到resource下,然后配置一下yml

    2024年02月02日
    瀏覽(100)
  • 【Java開發(fā)】Spring Cloud 11:Gateway 配置 ssl 證書(https、http、域名訪問)

    【Java開發(fā)】Spring Cloud 11:Gateway 配置 ssl 證書(https、http、域名訪問)

    最近研究給微服務(wù)項(xiàng)目配置 ssl 證書,如此才可以對(duì)接微信小程序(需要使用 https 請(qǐng)求)。傳統(tǒng)單體項(xiàng)目來說,首先往項(xiàng)目中添加證書文件,然后在配置文件中配置 ssl 證書路徑、密碼等相關(guān)信息;那么微服務(wù)這么多項(xiàng)目,總不能一個(gè)個(gè)配置 ssl 證書,最后發(fā)現(xiàn)可以直接通過網(wǎng)

    2024年02月08日
    瀏覽(87)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包