欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java中調用https請求忽略ssl證書認證代碼示例

 更新時間:2024年10月26日 09:07:33   作者:新時代農民~  
在網絡請求中經常會遇到需要忽略證書認證的情況,這篇文章主要介紹了java中調用https請求忽略ssl證書認證的相關資料,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下

1、獲取httpclient,忽略證書認證

public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有證書
                public boolean isTrusted(X509Certificate[] arg0, String arg1)
                        throws CertificateException {
                    return true;
                }
            }).build();
            // 創(chuàng)建主機名驗證器,用于繞過主機名驗證
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            // 創(chuàng)建 SSL 連接套接字工廠,將自定義的 SSL 上下文和主機名驗證器應用于 HTTPS 連接
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            // 創(chuàng)建自定義的 CloseableHttpClient 實例,將 SSL 連接套接字工廠應用于 HTTP 客戶端
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();
    }

2、使用put請求調用

   public static String put(String url, Map<String, String> header, String param) throws Exception {
        String result = "";
        StringEntity entity = new StringEntity(param, "utf-8");
        CloseableHttpClient httpClient = null;
        try {
            httpClient = createSSLClientDefault();
            HttpPut httpPut = new HttpPut(url);
            if (MapUtils.isNotEmpty(header)) {
                for (Map.Entry<String, String> entry : header.entrySet()) {
                    httpPut.addHeader(entry.getKey(), entry.getValue());
                }
            }
            if (entity != null) {
                entity.setContentType("application/json; charset=utf-8");
                httpPut.setEntity(entity);
            }
            LogUtil.info("開始請求https接口:" + url );
            HttpResponse httpResponse = httpClient.execute(httpPut);
            LogUtil.info("put請求返回httpResponse結果:" + httpResponse);
            HttpEntity resEntity = httpResponse.getEntity();
            result = EntityUtils.toString(resEntity, "UTF-8");
            LogUtil.info("put請求返回結果:" + result);
        } catch (Exception e) {
            throw e;
        } finally {
            if (httpClient != null) {
                httpClient.close();
            }
        }
        return result;
    }

總結 

到此這篇關于java中調用https請求忽略ssl證書認證的文章就介紹到這了,更多相關java調用https請求忽略ssl認證內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論