Request Payload 请求:
private static String xxxServerUrl = "http://xxx.xxx.xxx.xxx:xxxx/xxxxxxx";
@Resource
private RestTemplate restTemplate;
private ResResultPast sendPost(JSONObject jsonObject, String url) {
HttpHeaders headers = new HttpHeaders();
// 设置请求头
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<String> multiValueMapHttpEntity = new HttpEntity<>(jsonObject.toString(), headers);
ResResultPast response = restTemplate.postForObject(xxxServerUrl + url, multiValueMapHttpEntity, ResResultPast.class);
log.info("请求响应,response:{}", JSONObject.toJSONString(response));
return response;
}
使用时:
@Override
public Object queryList(xxxDto queryDto) {
JSONObject jsonObject = new JSONObject();
jsonObject.put("xxx1", queryDto.getxxx1());
jsonObject.put("xxx2", queryDto.getxxx2());
return sendPost(jsonObject, "/xxxxx/xxxxxx").getData();
}
FormData 请求:
private ResResultPast sendPostForm(MultiValueMap<String, Object> requestParam, String url) {
HttpHeaders headers = new HttpHeaders();
// 设置请求头
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
if (StpUtil.isLogin()) {
headers.add(StpUtil.getTokenName(), StpUtil.getTokenValue());
}
HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(requestParam, headers);
ResponseEntity<ResResultPast> response = restTemplate.postForEntity(xxxServerUrl + url, httpEntity, ResResultPast.class);
return response.getBody();
}
使用时:
public Object getxxxID(String id) {
MultiValueMap<String, Object> requestParam = new LinkedMultiValueMap<>();
requestParam.add("id", id);
return sendPostForm(requestParam, "/xxxx/xxxxx").getData();
}
Request Payload 请求,参数为List时
private ResResultPast sendPostArray(List<String> jsonList, String url) {
HttpHeaders headers = new HttpHeaders();
// 设置请求头
headers.setContentType(MediaType.APPLICATION_JSON);
String json = JSON.toJSONString(jsonList);
HttpEntity<String> multiValueMapHttpEntity = new HttpEntity<>(json, headers);
ResResultPast response = restTemplate.postForObject(xxxServerUrl + url, multiValueMapHttpEntity, ResResultPast.class);
log.info("请求响应,response:{}", JSONObject.toJSONString(response));
return response;
}
public Object xxxxx(List<String> ids) {
return sendPostArray(ids, "/xxxx/xxxxx").getData();
}
若请求到的中文出现乱码
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));