问题描述

有个项目接口需要传送一个x-www-form-urlencoded的参数,key=data,value={json的map}
一开始用一个字符串拼接,把字符串拼接为如下样式:

String param = "data=
{
    "aa": "123456789",
    "bb": "11",
    "cc": "梁宝宝"
}"

然后直接把这个字符串当做参数传过去:

RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8", true, true);
Map result = restTemplate.postForObject(URL, param , Map.class);

结果人家就返回报错说读取不到参数。

解决办法

设置请求头和设置请求参数,然后把封装过后的HttpEntity作为参数传过去,问题解决。

// 转换参数格式
String json = JSON.toJSONString(params);

// 设置请求头
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Type", "application/x-www-form-urlencoded");
// 设置请求参数
MultiValueMap<String, Object> postParameters = new LinkedMultiValueMap<>();
postParameters.add("data", json);

HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(postParameters, headers);

RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8", true, true);
Map result = restTemplate.postForObject(URL, httpEntity, Map.class);
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐