RestTemplate发送添加Header和Body

使用RestTempalate发送HTTP请求时,会有发送自定义Header和Body的需求,有一点错误就发送不出去,这里直接给出答案:

String token = easeToken.getAccess_token();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + token);
headers.add("Content-Type", "application/json");
Map requestBody = new HashMap<>(8);
requestBody.put("groupname", createChatGroupReqDto.getGroupname());
requestBody.put("desc", createChatGroupReqDto.getDesc());
requestBody.put("public", createChatGroupReqDto.getPublic2());
requestBody.put("maxusers", createChatGroupReqDto.getMaxusers());
requestBody.put("approval", createChatGroupReqDto.getApproval());
requestBody.put("owner", createChatGroupReqDto.getOwner());
requestBody.put("members", createChatGroupReqDto.getMembers());
log.info("createChatGroup|{}", requestBody);
HttpEntity> httpEntity = new HttpEntity<>(requestBody, headers);
ResponseEntity response = null;
try {
    response = restTemplate.postForEntity(CREATE_GROUP_URL, httpEntity, String.class);
} catch (HttpClientErrorException e) {
    log.error(e.getResponseBodyAsString(), e);
}

注意这里使用的是HashMap,当你没有添加Header的时候,如:

MultiValueMap paramMap = new LinkedMultiValueMap<>();
String response= restTemplate.postForObject(url, paramMap, String.class);

这里的Map使用的是MultiValueMap,注意区别,使用不当,服务端是接收不到参数的。

你可能感兴趣的:(SpringMVC,三方库使用)