学无先后,达者为师

网站首页 编程语言 正文

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

  • 上一篇:没有了
  • 下一篇:没有了
栏目分类
最近更新