不说废话,直接上一个笔者写的共通方法
/**
* post请求
*
* @param postUrl
* @param param
* @return java.lang.String
* @author He
* @date 2020/8/28 19:35
**/
public static <T> T post(String postUrl, Object param, Class<T> type) {
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
HttpHeaders headers = new HttpHeaders();
// 设置验签用的数据
// headers.add("Accept", MediaType.APPLICATION_JSON.toString());
// headers.add("Authorization", token);
// 设置content-type,很据需求设置
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
// 设置请求体
MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
String con = JSON.toJSONString(param);
map.add("param", con);
// 用HttpEntity封装整个请求报文
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
ResponseEntity<String> response = restTemplate.postForEntity(postUrl, request, String.class);
return JSON.parseObject(response.getBody(), type);
}
HttpClient对接方式,可查看笔者的另一篇文章《HttpClient接口调用》