一、RestTemplate 簡(jiǎn)介
Spring RestTemplate是Spring提供的用于訪問Rest服務(wù)的客戶端,RestTemplate 提供了多種便捷訪問遠(yuǎn)程Http服務(wù)的方法,能夠大大提高客戶端的編寫效率.
RestTemplate包含以下幾個(gè)部分:
HttpMessageConverter 對(duì)象轉(zhuǎn)換器:將請(qǐng)求對(duì)象轉(zhuǎn)換為具體的數(shù)據(jù)格式輸出,例
入:Jaxb2RootElementHttpMessageConverterket提供對(duì)xml格式的輸入輸出支持
ClientHttpRequestFactory HTTP請(qǐng)求工廠,默認(rèn)是JDK的HttpURLConnection,
可以通過使用ClientHttpRequestFactory指定不同的HTTP請(qǐng)求方式
ResponseErrorHandler 異常錯(cuò)誤處理
ClientHttpRequestInterceptor 請(qǐng)求攔截器
RestTemplate通過HttpEntity添加消息headers
二、springboot 通過RestTemplate實(shí)現(xiàn)https訪問
import java.io.InputStream; import java.security.KeyStore; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.net.ssl.TrustManager; import org.apache.commons.lang3.StringUtils; import org.apache.http.HttpHost; import org.apache.http.conn.ssl.SSLConnectionSocketFactory; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContexts; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Conditional; import org.springframework.context.annotation.Configuration; import org.springframework.http.MediaType; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.json.GsonHttpMessageConverter; import org.springframework.http.converter.xml.Jaxb2RootElementHttpMessageConverter; import org.springframework.web.client.RestTemplate; /** * service相關(guān)配置 * * @date 2017年3月1日 * @since 1.0.0 */ @Configuration public class ServiceConfigConfiguration { @Autowired sslProperties sslProperties ; /** * 訪問SSL的Template * * @throws Exception */ @Bean("sslRestTemplate") @Conditional(sslCondition.class) public RestTemplate tmsRestTemplate() throws Exception { //新建RestTemplate對(duì)象 RestTemplate restTemplate = new RestTemplate(); //判斷證書文件地址是否存在 if (StringUtils.isNotEmpty(sslProperties.getKeyfile())) { //在握手期間,如果URL的主機(jī)名和服務(wù)器的標(biāo)識(shí)主機(jī)名不匹配,則驗(yàn)證機(jī)制可以回調(diào)此接口的實(shí)現(xiàn) 程序來確定是否應(yīng)該允許此連接 HostnameVerifier hv = new HostnameVerifier() { @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); //構(gòu)建SSL-Socket鏈接工廠 SSLConnectionSocketFactory ssLSocketFactory = buildSSLSocketFactory("PKCS12", sslProperties.getKeyfile(),sslProperties.getPassword(), Lists.newArrayList("TLSv1"), true); //Spring提供HttpComponentsClientHttpRequestFactory指定使用HttpClient作為底層實(shí)現(xiàn)創(chuàng)建 HTTP請(qǐng)求 HttpComponentsClientHttpRequestFactory httpRequestFactory = new HttpComponentsClientHttpRequestFactory( HttpClients.custom().setSSLSocketFactory(ssLSocketFactory).build() ); //設(shè)置傳遞數(shù)據(jù)超時(shí)時(shí)長(zhǎng) httpRequestFactory.setReadTimeout(sslProperties.getTimeout()); //設(shè)置建立連接超時(shí)時(shí)長(zhǎng) httpRequestFactory.setConnectTimeout(sslProperties.getTimeout()); //設(shè)置獲取連接超時(shí)時(shí)長(zhǎng) httpRequestFactory.setConnectionRequestTimeout(tmsProperties.getTimeout()); restTemplate.setRequestFactory(httpRequestFactory); // 返回消息頭也是text_html,消息格式是XML,添加新的message converter Jaxb2RootElementHttpMessageConverter messageConverter = new Jaxb2RootElementHttpMessageConverter(); //設(shè)置message Converter支持的媒體類型 ListfinalMediaTypes = new ArrayList<>(); finalMediaTypes.addAll(messageConverter.getSupportedMediaTypes()); finalMediaTypes.add(MediaType.TEXT_HTML); messageConverter.setSupportedMediaTypes(finalMediaTypes); restTemplate.setMessageConverters(Lists.newArrayList(messageConverter)); } return restTemplate; } /** * 構(gòu)建SSLSocketFactory * * @param keyStoreType * @param keyFilePath * @param keyPassword * @param sslProtocols * @param auth 是否需要client默認(rèn)相信不安全證書 * @return * @throws Exception */ private SSLConnectionSocketFactory buildSSLSocketFactory(String keyStoreType, String keyFilePath, String keyPassword, List sslProtocols, boolean auth) throws Exception { //證書管理器,指定證書及證書類型 KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); //KeyStore用于存放證書,創(chuàng)建對(duì)象時(shí) 指定交換數(shù)字證書的加密標(biāo)準(zhǔn) KeyStore keyStore = KeyStore.getInstance(keyStoreType); InputStream inputStream = resourcePatternResolver.getResource(keyFilePath).getInputStream(); try { //添加證書 keyStore.load(inputStream, keyPassword.toCharArray()); } finally { inputStream.close(); } keyManagerFactory.init(keyStore, keyPassword.toCharArray()); SSLContext sslContext = SSLContext.getInstance("SSL"); if (auth) { // 設(shè)置信任證書(繞過TrustStore驗(yàn)證) TrustManager[] trustAllCerts = new TrustManager[1]; TrustManager trustManager = new AuthX509TrustManager(); trustAllCerts[0] = trustManager; sslContext.init(keyManagerFactory.getKeyManagers(), trustAllCerts, null); HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory()); } else { //加載證書材料,構(gòu)建sslContext sslContext = SSLContexts.custom().loadKeyMaterial(keyStore, keyPassword.toCharArray()).build(); } SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, sslProtocols.toArray(new String[sslProtocols.size()]), null, new HostnameVerifier() { // 這里不校驗(yàn)hostname @Override public boolean verify(String urlHostName, SSLSession session) { return true; } }); return sslConnectionSocketFactory; } }
AuthX509TrustManager 證書信任管理器類就是實(shí)現(xiàn)了接口X509TrustManager的類??梢宰约簩?shí)現(xiàn)該接口,信任我們指定的證書
public class AuthX509TrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } }
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://www.ezyhdfw.cn/yun/69126.html
摘要:調(diào)用的默認(rèn)構(gòu)造函數(shù),對(duì)象在底層通過使用包下的實(shí)現(xiàn)創(chuàng)建請(qǐng)求,可以通過使用指定不同的請(qǐng)求方式。接口主要提供了兩種實(shí)現(xiàn)方式一種是,使用提供的方式既包提供的方式創(chuàng)建底層的請(qǐng)求連接。 showImg(http://download.qfeoo.com/kotlin_springboot_logo.png); 自從RESTFul API興起后,Spring就給開發(fā)者提供了一個(gè)訪問Rest的客服端,...
摘要:也是提交新資源,提交成功之后,返回新資源的,的參數(shù)和前面兩種的參數(shù)基本一致,只不過該方法的返回值為,這個(gè)只需要服務(wù)提供者返回一個(gè)即可,該表示新資源的位置。用于操作請(qǐng)求頭和,在請(qǐng)求發(fā)出前執(zhí)行。 showImg(https://segmentfault.com/img/remote/1460000012261105?w=1873&h=1080); 背景 這段時(shí)間自己做的項(xiàng)目中需要調(diào)用服務(wù)提...
摘要:如果去掉,你會(huì)發(fā)現(xiàn),執(zhí)行這三個(gè)方法都在線程中執(zhí)行。耗時(shí)總結(jié),如下耗時(shí)通過這一個(gè)小的栗子,你應(yīng)該對(duì)異步任務(wù)有了一定的了解。 這篇文章主要介紹在springboot 使用異步方法,去請(qǐng)求github api. 創(chuàng)建工程 在pom文件引入相關(guān)依賴: org.springframework.boot spring-boot-starter ...
摘要:環(huán)境搭建注冊(cè)中心依賴如下所示配置應(yīng)用啟動(dòng)端口注冊(cè)中心管理中的應(yīng)用名稱登陸注冊(cè)管理中的的賬號(hào)密碼是否把自己注冊(cè)到注冊(cè)中心是否從上來獲取服務(wù)的注冊(cè)信息啟動(dòng)注冊(cè)中心啟動(dòng)后訪問登陸界面輸入設(shè)置的賬號(hào)密碼進(jìn) 環(huán)境 Java version 1.8 SpringBoot version 2.1.7 搭建注冊(cè)中心 Eureka-server pom.xml 依賴如下所示: ...
閱讀 3397·2023-04-25 16:25
閱讀 3953·2021-11-15 18:01
閱讀 1678·2021-09-10 11:21
閱讀 3173·2021-08-02 16:53
閱讀 3156·2019-08-30 15:55
閱讀 2554·2019-08-29 16:24
閱讀 2166·2019-08-29 13:14
閱讀 1109·2019-08-29 13:00