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

SpringBoot 使用RestTemplate來調(diào)用https接口

這篇具有很好參考價值的文章主要介紹了SpringBoot 使用RestTemplate來調(diào)用https接口。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

項目場景:

使用RestTemplate來訪問第三方https接口,接口類型為POST,返回數(shù)據(jù)為JSON,需要忽略https證書,因此對RestTemplate 進行配置,通過HttpClient的請求工廠(HttpComponentsClientHttpRequestFactory)進行構(gòu)建。HttpComponentsClientHttpRequestFactory使用一個信任所有站點的HttpClient就可以解決問題了。


問題描述

中間踩坑:
報錯內(nèi)容:

no suitable HttpMessageConverter found for response type [class cn.smxy.testSpring.vo.TokenVO] and content type [application/octet-stream]

沒有為響應類型 [class cn.smxy.testSpring.vo.TokenVO] 和內(nèi)容類型 [applicationoctet-stream] 找到合適的 HttpMessageConverter


解決方案:

全局配置中加上
mediaTypes.add(MediaType.APPLICATION_JSON);
mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);

package cn.smxy.testSpring.config;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

public class HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    public HttpMessageConverter(){
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        setSupportedMediaTypes(mediaTypes);
    }
}

完整代碼:

配置pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
</dependency>

1.創(chuàng)建一個SSL類代碼如下

跳過證書驗證,信任所有站點的HttpClient

package cn.smxy.testSpring.util;

import org.springframework.http.client.SimpleClientHttpRequestFactory;

import javax.net.ssl.*;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;

/**
 * @author nzh
 * @date 2022/8/22 16:45
 */
public class SSL extends SimpleClientHttpRequestFactory {
    @Override
    protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
        if (connection instanceof HttpsURLConnection) {
            prepareHttpsConnection((HttpsURLConnection) connection);
        }
        super.prepareConnection(connection, httpMethod);
    }

    private void prepareHttpsConnection(HttpsURLConnection connection) {
        connection.setHostnameVerifier(new SkipHostnameVerifier());
        try {
            connection.setSSLSocketFactory(createSslSocketFactory());
        } catch (Exception ex) {
            // Ignore
        }
    }

    private SSLSocketFactory createSslSocketFactory() throws Exception {
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, new TrustManager[] { new SkipX509TrustManager() }, new SecureRandom());
        return context.getSocketFactory();
    }

    private class SkipHostnameVerifier implements HostnameVerifier {

        @Override
        public boolean verify(String s, SSLSession sslSession) {
            return true;
        }

    }

    private static class SkipX509TrustManager implements X509TrustManager {

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return new X509Certificate[0];
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

    }
}

2.自定義HttpMessageConverter類,繼承MappingJackson2HttpMessageConverter 消息轉(zhuǎn)換器

package cn.smxy.testSpring.config;

import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.util.ArrayList;
import java.util.List;

public class HttpMessageConverter extends MappingJackson2HttpMessageConverter {
    public HttpMessageConverter(){
        List<MediaType> mediaTypes = new ArrayList<>();
        mediaTypes.add(MediaType.TEXT_PLAIN);
        mediaTypes.add(MediaType.TEXT_HTML);
        mediaTypes.add(MediaType.APPLICATION_JSON);
        mediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
        setSupportedMediaTypes(mediaTypes);
    }
}

3.創(chuàng)建一個RestTemplateConfig類代碼如下:


package cn.smxy.testSpring.config;

import cn.smxy.testSpring.util.SSL;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
 
/**   
 * @ClassName:  RestTemplateConfig   
 * @Description:  RestTemplate配置類
 * @author: nzh
 */
@Configuration
public class RestTemplateConfig {
 
	@Bean
	public RestTemplate restTemplate( ClientHttpRequestFactory factory) {
		RestTemplate restTemplate = new RestTemplate(factory);
		// 支持中文編碼
		restTemplate.getMessageConverters().add(new HttpMessageConverter());
		return restTemplate;
	}
 
	@Bean
	public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
		SSL factory = new SSL(); //這里使用剛剛配置的SSL
		// SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
		factory.setReadTimeout(5000);//單位為ms
		factory.setConnectTimeout(5000);//單位為ms
		return factory;
	}
}
 

4.調(diào)用代碼,單元測試 MultiValueMap,LinkedMultiValueMap別改 否則參數(shù)會傳輸失敗文章來源地址http://www.zghlxwxcb.cn/news/detail-534102.html


@SpringBootTest(classes = TestSpringApplication.class)
@RunWith(SpringRunner.class)

public class SpringApplicationTests {

    @Test
    public void contextLoads() {
        // 請求頭信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf("application/x-www-form-urlencoded"));
        //設(shè)置為表單提交,按需求加
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        // 組裝請求信息
        MultiValueMap<String, String> params= new LinkedMultiValueMap<String, String>();
        //  也支持中文
        params.add("userName", "你的用戶名");
        params.add("password", "你的密碼");
        HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<MultiValueMap<String, String>>(params, headers);
        //VO是接口返回類
        TokenVO tokenVO = restTemplate.postForObject("你的接口地址", requestEntity, TokenVO.class);
        System.out.println(tokenVO);
    }
}

到了這里,關(guān)于SpringBoot 使用RestTemplate來調(diào)用https接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

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

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

相關(guān)文章

  • RestTemplate 請求https接口,無需證書訪問,并整合工具類,細到極致

    ??Hello,大家好呀,我是你們的Jessica老哥,不知不覺,到了3月份了,又是一年一度的金三銀四,老哥和大家一樣,想換工作,于是呢,更新資料,投簡歷。試想著把自己的勞動價值賣的更高一點。 ??沒想到,今年好像行情有點不太對勁呀,往年跟HR打個招呼,人家還會要你

    2024年02月08日
    瀏覽(20)
  • 使用RestTemplate訪問https實現(xiàn)SSL請求操作,設(shè)置TLS版本

    注意:服務(wù)端TLS版本要和客戶端工具類中定義的一致, 當支持的是列表時,能夠與不同版本的客戶端進行通信,在握手期間,TLS會選擇兩者都支持的最高的版本 javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure解決方案 方法升級JDK版本 全局設(shè)置優(yōu)先級 代碼里面的設(shè)置

    2024年02月01日
    瀏覽(17)
  • SpringBoot中的RestTemplate使用筆記

    以下代碼是基于SpringBoot2.4.2版本寫的案例 需要配置的application.yml如下 restTemplate日志攔截器 定義一些API接口 測試使用RestTemplateUtil

    2024年02月15日
    瀏覽(24)
  • Java工具類:使用RestTemplate請求WebService接口

    對接第三方提供的 WebService 接口,早期的調(diào)用方式過于復雜繁瑣,所以使用 RestTemplate 進行調(diào)用 注:除了 RestTemplate 之外, HttpURLConnection 等也可以用來調(diào)用webservice接口 如果需要將xml轉(zhuǎn)為Json,可參考:

    2024年01月22日
    瀏覽(22)
  • SpringBoot中RestTemplate的使用備忘

    2-1 引入Maven依賴 2-2 創(chuàng)建 RestTemplate 配置類,設(shè)置連接池大小、超時時間、重試機制等等。 4-1 使用示例 4-2 參數(shù)傳遞的幾種方式 5-1 使用示例 5-2 參數(shù)傳遞的幾種方式 6-1 使用示例 6-2 設(shè)置 url 參數(shù),同Get請求 7-1 使用示例,和postForObject()基本相似,返回的是ResponseEntity罷了 7-2 設(shè)置

    2024年02月02日
    瀏覽(15)
  • SpringBoot 使用 RestTemplate 發(fā)送 binary 數(shù)據(jù)流

    SpringBoot 使用 RestTemplate 發(fā)送 binary 數(shù)據(jù)流

    情況說明: 接口A接受到一個數(shù)據(jù)流,在postman里的傳輸方式顯示如下: 接口A接受到這個數(shù)據(jù)流之后,需要轉(zhuǎn)發(fā)到接口B進行處理。 這里要注意一點是: postman圖中的這種方式和MultipartFile流的傳輸方式不同,MultipartFile流方式,是在body的form表單中進行傳輸,需要指定一個key,這

    2024年02月12日
    瀏覽(20)
  • SpringBoot | RestTemplate異常處理器ErrorHandler使用詳解

    SpringBoot | RestTemplate異常處理器ErrorHandler使用詳解

    關(guān)注wx:CodingTechWork ??在代碼開發(fā)過程中,發(fā)現(xiàn)很多地方通過 RestTemplate 調(diào)用了第三方接口,而第三方接口需要根據(jù)某些狀態(tài)碼或者異常進行重試調(diào)用,此時,要么在每個調(diào)用的地方進行異常捕獲,然后重試;要么在封裝的 RestTemplate 工具類中進行統(tǒng)一異常捕獲和封裝。當然

    2024年02月12日
    瀏覽(17)
  • 【SpringBoot】springboot使用RestTemplate 進行http請求失敗自動重試

    【SpringBoot】springboot使用RestTemplate 進行http請求失敗自動重試

    我們的服務(wù)需要調(diào)用別人的接口,由于對方的接口服務(wù)不是很穩(wěn)定,經(jīng)常超時,于是需要增加一套重試邏輯。這里使用 Spring Retry 的方式來實現(xiàn)。 一、引入POM 二、 修改啟動類 在Spring Boot 應用入口啟動類,也就是配置類的上面加上 @EnableRetry 注解,表示讓重試機制生效。 注意

    2024年02月08日
    瀏覽(19)
  • restTemplate轉(zhuǎn)發(fā)Https請求

    restTemplate轉(zhuǎn)發(fā)Https請求

    代碼架構(gòu) 效果

    2024年02月08日
    瀏覽(16)
  • SpringBoot之RestTemplate使用Apache的HttpClient連接池

    SpringBoot自帶的RestTemplate是沒有使用連接池的,只是SimpleClientHttpRequestFactory實現(xiàn)了ClientHttpRequestFactory、AsyncClientHttpRequestFactory 2個工廠接口,因此每次調(diào)用接口都會創(chuàng)建連接和銷毀連接,如果是高并發(fā)場景下會大大降低性能。因此,我們可以使用Apache的HttpClient連接池。

    2024年02月11日
    瀏覽(19)

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

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

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

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包