日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

restTemplate使用總結

作者:蔚藍色的風暴 更新時間: 2024-07-18 編程語言

1、配置類

@Configuration
public class RestTemplateConfig() {
	@Bean
	public RestTemplate restTemplate(ClientHttpRequestFactory factory) {
		return new RestTemplate(factory);
	}

	@Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory() {
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setConnectTimeout(300000);
        factory.setReadTimeout(300000);
        return factory;
    }
}

實際使用時可以生成不同的factory

// 不進行證書校驗
RestTemplate restTemplateHttps = new RestTemplate(RestTemplateConfig.generateHttpRequestFactory());

public static HttpComponentsClientHttpRequestFactory generateHttpRequestFactory()
            throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException {
        TrustStrategy acceptingTrustStrategy = (x509Certificates, authType) -> true;
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
        SSLConnectionSocketFactory connectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new NoopHostnameVerifier());
        HttpClientBuilder httpClientBuilder = HttpClients.custom();
        httpClientBuilder.setSSLSocketFactory(connectionSocketFactory);
        CloseableHttpClient httpClient = httpClientBuilder.build();
        HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory();
        factory.setHttpClient(httpClient);
        return factory;
    }

2、發送請求

(1)restTemplate.exchange

// get
HttpEntity<MyDTO> httpEntity = new HttpEntity<>(inputBody,headers)
ResponseEntity<Map> exchange = restTemplate.exchange(url,HttpMethod.GET,httpEntity,Map.class)

// Post
HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<Map<String, Object>>(params, headers);
            ResponseEntity<refreshUeResultDTO> ret = restTemplate.exchange(restfulUrl, HttpMethod.POST, httpEntity,
                    refreshUeResultDTO.class);

(2) restTemplate.getForEntity

ResponseEntity<String> ret = restTemplate.getForEntity(restful, String.class, new HashMap<>());

getForEntity沒法直接攜帶header

(3)restTemplate.postForEntity

HttpEntity<EspaceMessageDTO> httpEntity = new HttpEntity<>(espaceMessageDTO,headers);
            ResponseEntity<Object> res = restTemplate.postForEntity(url,httpEntity, Object.class);

(4)接收的類帶泛型

ResponseEntity<List<RundeckTaskDO>> result = restTemplate.exchange(restful, HttpMethod.GET, entity, new ParameterizedTypeReference<List<RundeckTaskDO>>() {
            });

原文鏈接:https://blog.csdn.net/qq_37831759/article/details/140024485

  • 上一篇:沒有了
  • 下一篇:沒有了
欄目分類
最近更新