public static <T> ResponseEntity<T> request(String url,
HttpMethod httpMethod,
Class<T> responseType,
Map<String,String> headers,
Map<String,String> params,
Map<String,String> body) {
//设置请求参数
MultiValueMap<String, String> paramsMap = new LinkedMultiValueMap<>();
if(CollUtil.isNotEmpty(params)){
params.forEach(paramsMap::add);
}
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
URI uri = builder.queryParams(paramsMap).build().encode().toUri();
// 设置请求头
HttpHeaders httpHeaders = new HttpHeaders();
// 传递请求体时必须设置
httpHeaders.add("Content-Type", "application/json");
if( CollUtil.isNotEmpty(headers) ){
headers.forEach(httpHeaders::add);
}
// 设置请求头和请求体
HttpEntity<String> httpEntity = new HttpEntity<>(JSONUtil.toJsonStr(body), httpHeaders);
return restTemplate.exchange(uri,httpMethod,httpEntity,responseType);
}
RestTemplate请求时设置请求头,请求参数,请求体。
最新推荐文章于 2024-02-25 13:53:08 发布