带有标题和正文的Spring RestTemplate POST查询

时间:2018-03-21 03:41:20

标签: spring rest

我需要使用给定的API定义,但是我无法在documentation找到同时接收标头和请求主体的函数调用。请在此处建议使用RestTemplate的哪个功能。

@RequestMapping(value = "/createObject", method = RequestMethod.POST,
        consumes = MediaType.APPLICATION_JSON_VALUE, 
        produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<CreateObjectOutput> createObject(
        @RequestBody CreateObjectInput req) 
{
    CreateObjectOutput out = new CreateObjectOutput();
    ///// Some Code
    return new ResponseEntity<CreateObjectOutput>(out, HttpStatus.OK);
}

2 个答案:

答案 0 :(得分:6)

RestTemplate template = new RestTemplate();
CreateObjectInput payload = new CreateObjectInput();

HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);

HttpEntity<CreateObjectOutput> requestEntity = 
     new HttpEntity<>(payload, headers);
CreateObjectOutput response = 
   template.exchange("url", HttpMethod.POST, requestEntity, 
              CreateObjectOutput.class);

答案 1 :(得分:0)

//Inject you rest template
@Autowired
RestTemplate restTmplt;

然后在你的方法中使用它。

HttpHeaders header = new HttpHeaders();

//You can use more methods of HttpHeaders to set additional information
header.setContentType(MediaType.APPLICATION_JSON);

Map<String, String> bodyParamMap = new HashMap<String, String>();

//Set your request body params
bodyParamMap.put("key1", "value1");
bodyParamMap.put("key2", "value2");
bodyParamMap.put("key3", "value3");

您可以使用将您的请求正文转换为JSON格式的字符串 ObjectMapper的writeValueAsString()方法。

String reqBodyData = new ObjectMapper().writeValueAsString(bodyParamMap);

HttpEntity<String> requestEnty = new HttpEntity<>(reqBodyData, header);

POST方法的postForEntity() GET方法的getForEntity()

ResponseEntity<Object> result = restTmplt.postForEntity(reqUrl, requestEnty, Object.class);
        return result;

ObjectMapper是杰克逊的依赖 com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper()

取代ResponseEntity Object类,它也可以是您自己的类,也可以基于您期望的响应。

例如:

ResponseEntity<Demo> result = restTmplt.postForEntity(reqUrl, requestEnty, Demo.class);