使⽤RestTemplate在代码内调⽤POST请求的参数乱码问题
背景:在项⽬A代码内部,调⽤项⽬B的restful接⼝C,我们采⽤了RestTemplate进⾏调⽤,但是调⽤过程中,⼀直不能正常返回数据,⽇志显⽰参数存在乱码(有个参数的值是中⽂)
乱码原因:请求⽅式是POST,但是我们把参数都放在了url的?后⾯,参数传递形式与GET请求⼀样
由于请求⽅式是POST,所以需要将参数放在body⾥⾯进⾏传递,并且参数需要⽤MultiValueMap结构体装载,如下所⽰(RestTemplate的调⽤改为如下就好了):
⽅式⼀:
if (method == HttpMethod.POST) {
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
map.forEach((k, v) -> {
postParameters.add(k, v.toString());
});
return JSON.parseObject(restTemplate.postForObject(url, postParameters, String.class));
}
⽅式⼆:
postParam: post请求时body⾥⾯的参数
url: 含url后跟的其他参数
restTemplate.String(), new HttpEntity<>(postParam), String.class);
注意,在启动类⾥加载restTemplate时,需要设置为UTF-8
@Bean
public RestTemplate getRestTemplate() {
RestTemplate restTemplate = new RestTemplate();
return restTemplate;
}
⽅式三:
适合于 url 后⾯既有 param ⼜有 body 的 post 请求
public void testPostRestTemplate() {
String url = "localhost:9999/xxx/xxx";
// url 后⾯的 param 参数,即 url 问号后⾯的参数信息
Map<String, Object> urlMap = new HashMap<>(5);
urlMap.put("urlKey1", "urlValue1");
urlMap.put("urlKey2", "urlValue2");
urlMap.put("urlKey3", "urlValue3");
urlMap.put("urlKey4", "urlValue4");
urlMap.put("urlKey5", "urlValue5");
// 将 param 参数追加到 url 后⾯
StringBuilder sb = new StringBuilder(url);
if (!CollectionUtils.isEmpty(urlMap)) {
sb.append("?");
urlMap.forEach((k, v) -> {
sb.append(k).append("=").append(v).append("&");
});
sb.deleteCharAt(sb.length() - 1);
}
/
/ post 请求⾥⾯的 body 内容
Map<String, String> bodyMap = new HashMap<>();
bodyMap.put("bodyKey1", "bodyValue1");
// 设置 headers
HttpHeaders httpHeaders = new HttpHeaders();
MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
httpHeaders.setContentType(type);
HttpEntity<Map<String, Object>> objectHttpEntity = new HttpEntity(bodyMap, httpHeaders);
ResponseEntity<Object> responseResultResponseEntity = restTemplate.String(), objectHttpEntity, Object.class);
Object res = Body();
restful接口调用实例System.out.println(res);
}