1.首先需要导入依赖
<!-- RestTemplate使用导入的依赖--><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId><version>4.5.13</version></dependency>
2.跟启动类同级创建RestTemplateConfig
类
package com.gree.server;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.HttpClient;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.TrustStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/*** 创建RestTemplate配置类,设置连接池大小、超时时间、重试机制等。*/
@Configuration
@Slf4j
public class RestTemplateConfig {@Beanpublic RestTemplate restTemplate(){RestTemplate restTemplate = new RestTemplate();restTemplate.setRequestFactory(clientHttpRequestFactory());restTemplate.setErrorHandler(new DefaultResponseErrorHandler());return restTemplate;}@Beanpublic HttpComponentsClientHttpRequestFactory clientHttpRequestFactory() {try {HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {@Overridepublic boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {return true;}}).build();httpClientBuilder.setSSLContext(sslContext);HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslConnectionSocketFactory).build(); //注册http和https请求//开始设置连接池PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); //创建连接池poolingHttpClientConnectionManager.setMaxTotal(500); // 最大连接数500poolingHttpClientConnectionManager.setDefaultMaxPerRoute(100); // 同路由并发数100httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager);httpClientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler(3, true)); // 重试次数HttpClient httpClient = httpClientBuilder.build();HttpComponentsClientHttpRequestFactory clientHttpRequestFactory = new HttpComponentsClientHttpRequestFactory(httpClient); // httpClient连接配置clientHttpRequestFactory.setConnectTimeout(20000); // 连接超时clientHttpRequestFactory.setReadTimeout(30000); // 数据读取超时时间clientHttpRequestFactory.setConnectionRequestTimeout(20000); // 连接不够用的等待时间return clientHttpRequestFactory;} catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) {log.error("初始化HTTP连接池出错", e);}return null;}
}
3.调用第三方接口
采纳https://www.python100.com/html/111748.html
设置Header,即在调用RestTemplate的exchange()方法时,传递参数,该参数包含了请求头和请求体。下面以设置Authorization为例
@GetMapping("/hello/getForObject")public ResponseEntity getForObject(){String url="http://localhost:8079/hello";//调用的第三方地址HttpHeaders headers = new HttpHeaders();String accessToken="eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImNyZWF0ZWQiOjE2OTAwMDI5NTI4NzksImV4cCI6MTY5MDYwNzc1Mn0.VNE67W_DHYTWangmgHhcieUATW5BKtEYnr5A8HseLdp5gVFhAxGcHNRgBWjEOsERDGD8rWOLbVwXuJocGUkivw";headers.setContentType(MediaType.APPLICATION_JSON);headers.set("Authorization", "Bearer " + accessToken);HttpEntity entity = new HttpEntity<>(headers);ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);return response;}
问题设置动态获取token
上面我们获取的accessToken是写死的,那我们token有过期时间的话我们怎么处理,那就要处理accessToken,使其获取方式为动态的
主要添加请求头Authorization的方法如下
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.set("Authorization", "Bearer " + accessToken);HttpEntity entity = new HttpEntity<>(headers);ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
设置Header的编码,如使用Basic认证时,需要将用户名和密码编码为base64。在RestTemplate中,可以通过使用HttpHeaders的add()方法设置Header,该方法允许设置Header的值和编码方式。
HttpHeaders headers = new HttpHeaders();
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(Charset.forName("US-ASCII")));
String authHeader = "Basic " + new String(encodedAuth);headers.add("Authorization", authHeader);HttpEntity entity = new HttpEntity<>(headers);ResponseEntity response = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);