1、引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
2、配置restTemplate
@Bean
public RestTemplate getRestTemplate() {
try {
TrustStrategy acceptingTrustStrategy = (x509Certificates, em) -> true;
SSLContext sslContext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
requestFactory.setHttpClient(httpClient);
return new RestTemplate(requestFactory);
} catch (Exception e) {
log.error("getRestTemplate error.", e);
}
return new RestTemplate();
}
3、创建工具类
@Component
public class RestUtils {
@Autowired
private RestTemplate restTemplate;
public <T> T get(String url, Class<T> responseType) {
Map<String, String> httpHeaderMap = new HashMap<>();
httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
return sendRequest(url, HttpMethod.GET, null, responseType, httpHeaderMap);
}
public <T> T post(String url, Object requestBody, Class<T> responseType) {
Map<String, String> httpHeaderMap = new HashMap<>();
httpHeaderMap.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
httpHeaderMap.put(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE);
return sendRequest(url, HttpMethod.POST, requestBody, responseType, httpHeaderMap);
}
public <T> T sendRequest(String url, HttpMethod method, Object requestBody, Class<T> responseType, Map<String, String> httpHeaderMap) {
HttpHeaders headers = new HttpHeaders();
httpHeaderMap.keySet().forEach(key -> {
headers.add(key,httpHeaderMap.get(key));
});
HttpEntity<Object> entity = new HttpEntity<>(requestBody, headers);
return restTemplate.exchange(url, method, entity, responseType).getBody();
}
public String getParamUrl(String url, Map<String, String> paramMap) {
StringBuilder sb = new StringBuilder(url);
if (paramMap != null && !paramMap.isEmpty()) {
sb.append("?");
for (Map.Entry<String, String> entry : paramMap.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
sb.append(key).append("=").append(value).append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}