一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 使用RestTemplate訪問https實現SSL請求操作

使用RestTemplate訪問https實現SSL請求操作

2022-03-06 13:11一棵樹~ Java教程

這篇文章主要介紹了使用RestTemplate訪問https實現SSL請求操作,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

方法1: 用java生成證書,不建議,移植性差。

方法2: 將RestTemplate改為https請求。

1、添加HttpsClientRequestFactory工具類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.security.cert.X509Certificate;
 
/**
 * TLS的三個作用:
 *  (1)身份認證
 *      通過證書認證來確認對方的身份,防止中間人攻擊
 *  (2)數據私密性
 *      使用對稱性密鑰加密傳輸的數據,由于密鑰只有客戶端/服務端有,其他人無法窺探。
 *  (3)數據完整性
 *      使用摘要算法對報文進行計算,收到消息后校驗該值防止數據被篡改或丟失。
 *    
 *     使用RestTemplate進行HTTPS請求訪問:
 *  private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());
 *
 */
public class HttpsClientRequestFactory extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) {
        try {
            if (!(connection instanceof HttpsURLConnection)) {
                throw new RuntimeException("An instance of HttpsURLConnection is expected");
            }
 
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {
                        }
                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {
                        }
                    }
            };
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            httpsConnection.setSSLSocketFactory(new MyCustomSSLSocketFactory(sslContext.getSocketFactory()));
 
            httpsConnection.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }
            });
 
            super.prepareConnection(httpsConnection, httpMethod);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private static class MyCustomSSLSocketFactory extends SSLSocketFactory {
        private final SSLSocketFactory delegate;
        public MyCustomSSLSocketFactory(SSLSocketFactory delegate) {
            this.delegate = delegate;
        }
 
        // 返回默認啟用的密碼套件。除非一個列表啟用,對SSL連接的握手會使用這些密碼套件。
        // 這些默認的服務的最低質量要求保密保護和服務器身份驗證
        @Override
        public String[] getDefaultCipherSuites() {
            return delegate.getDefaultCipherSuites();
        }
 
        // 返回的密碼套件可用于SSL連接啟用的名字
        @Override
        public String[] getSupportedCipherSuites() {
            return delegate.getSupportedCipherSuites();
        }
 
        @Override
        public Socket createSocket(final Socket socket, final String host, final int port,
                                   final boolean autoClose) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(socket, host, port, autoClose);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final String host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final String host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final InetAddress host, final int port) throws IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port);
            return overrideProtocol(underlyingSocket);
        }
 
        @Override
        public Socket createSocket(final InetAddress host, final int port, final InetAddress localAddress,
                                   final int localPort) throws
                IOException {
            final Socket underlyingSocket = delegate.createSocket(host, port, localAddress, localPort);
            return overrideProtocol(underlyingSocket);
        }
 
        private Socket overrideProtocol(final Socket socket) {
            if (!(socket instanceof SSLSocket)) {
                throw new RuntimeException("An instance of SSLSocket is expected");
            }
            //((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1.2"});
            ((SSLSocket) socket).setEnabledProtocols(new String[]{"TLSv1", "TLSv1.1", "TLSv1.2"});
            return socket;
        }
    }
}

注意:服務端TLS版本要和客戶端工具類中定義的一致。(TLSv1.2)

2、修改RestTemplate

在使用的時候,將

?
1
private static RestTemplate restTemplate = new RestTemplate();

改為:

?
1
private static RestTemplate restTemplate = new RestTemplate(new HttpsClientRequestFactory());

其他代碼不變。

也可使用注入的方式:

?
1
2
3
4
5
6
7
@Configuration
public class ConfigBean {
 @Bean
 public RestTemplate getRestTemplate() {
  return new RestTemplate(new HttpsClientRequestFactory());
 }
}

3、訪問https,拋出的異常

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure解決方案

因為jdk中jce的安全機制導致報的錯,需要去oracle官網下載對應的jce包替換jdk中的jce包。

方案一:替換jce包

?
1
2
3
4
5
6
7
目錄 %JAVA_HOME%\jre\lib\security里的local_policy.jar,US_export_policy.jar
JDK7 http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html
JDK8 http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html
 
// pub1:/home/myron/jdk1.7.0_80 % cd $JAVA_HOME/jre/lib/security/  //jce所在jdk的路徑
US_export_policy.jar
local_policy.jar

方案二:升級 JDK到1.8版本(推薦方式)

?
1
2
3
4
5
// pub1:/home/myron % vi .cshrc
setenv JAVA_HOME /home/myron/jdk1.8.0_211
// pub1:/home/myron % source .cshrc
// pub1:/home/myron % java -version
java version "1.8.0_211"

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/MyronCham/article/details/103481046

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 女黑人尺寸bbb | 女bbbxxx毛片视频 | 精品国产乱码久久久久久免费 | 秋霞黄色大片 | 日本五十路六十30人8时间 | 秋霞午夜视频在线观看 | 嫩草在线视频www免费观看 | 天天色综合久久 | 美国高清xxxxx18 | 成人在线一区二区三区 | 久久精品国产亚洲AV热无遮挡 | 国产在线影院 | 精品久久伦理中文字幕 | aaa毛片视频免费观看 | 四虎e234hcom | 亚洲国产精品91 | 亚洲伦理影院 | 国产网站免费看 | 欧美乱理伦另类视频 | 四缺一写的小说 | 91视在线国内在线播放酒店 | 大伊香蕉在线精品不卡视频 | 蜜桃影像传媒推广 | 久久久乱码精品亚洲日韩 | 人人爽人人射 | 日本成人免费在线视频 | 免费视频片在线观看大片 | 国产精品免费_区二区三区观看 | 亚洲精品国产一区二区第一页 | 青青青久在线视频免费观看 | 成人免费影院 | 99热碰| 亚洲va国产日韩欧美精品色婷婷 | 亚洲无限观看 | 91色香sxmv最网页版新地址 | zol中关村在线官网 yy6080欧美三级理论 | 色综合天天综合网国产人 | 国产精品日韩欧美在线 | 精品久久免费观看 | 四虎影视4hutv最新地址在线 | 茄子视频懂你更多apl |