具有请求参数的RestTemplate POST请求

时间:2018-07-25 21:40:04

标签: java spring resttemplate

我正在使用Spring的RestTemplate将带有请求参数和请求标头的POST请求发送到我的RestController。

它失败,并显示以下错误消息:POST request for "[myurl]" resulted in 404 (null); invoking error handler

请注意,"[myurl]""http://localhost:8080/test"

这是我的代码:

RestTemplate rest = new RestTemplate();
MultiValueMap<String, Integer> map = new LinkedMultiValueMap<String, Integer>();
map.add("num1", 1);//request parameters
map.add("num2", 2);
HttpHeaders headers = new HttpHeaders();//request header
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<MultiValueMap<String, Integer>> request = new HttpEntity<MultiValueMap<String, Integer>>(map, headers);
Object obj = rest.postForObject("[myurl]", request, Object.class);
logger.log("Returned object: " + obj.toString());

1 个答案:

答案 0 :(得分:0)

也许尝试做类似的事情(如果可以使用MultiValueMap逃脱):

RestTemplate rest = new RestTemplate();
Map<String, Integer> map = new HashMap<>();
map.put("num1", 1);//request parameters
map.put("num2", 2);

Object obj = rest.postForObject("[myurl]", map, Object.class);
logger.log("Returned object: " + obj.toString());