RestTemplate发送x-www-form-urlencoded的数据
问题描述有个项目接口需要传送一个x-www-form-urlencoded的参数,key=data,value={json的map}一开始用一个字符串拼接,把字符串拼接为如下样式:String param = "data={"aa": "123456789","bb": "11","cc": "梁宝宝"}"然后直接把这个字符串当做参数传过去:RestTemplate restTemplate =
·
问题描述
有个项目接口需要传送一个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);
更多推荐
已为社区贡献1条内容
所有评论(0)