RestTemplate 封装 - RestUtils
1、引入依赖<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.apach
·
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 {
// 配置后可以使用 https
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;
/**
* 发送 get 请求
* 默认:客户端接受 json 类型数据
*/
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);
}
/**
* 发送 post 请求
* 默认:服务器接受 json 类型数据,客户端接受 json 类型数据
*/
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);
}
/**
* 发送请求
* @param method 请求方式
*/
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();
}
/**
* 在 url 后面拼接参数
* @param url 原请求路径
* @param paramMap 参数map
*/
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();
}
}
更多推荐


所有评论(0)