我有三个字段:SystemId
,RegionCode
和Locale
。我必须使用RestTemplate在头文件中发送这三个字段。我正在使用此代码:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String("RegionCode",regionCode);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
如何在标题中添加其余两个字段?
答案 0 :(得分:2)
也许您可以尝试以下方法:
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.put("RegionCode", regionCode);
headers.put("SystemId", systemId);
headers.put("Locale", locale);
HttpEntity<String> entity = new HttpEntity<String>(body,headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
答案 1 :(得分:0)
This is one of the example I have created:-
/********This is controller getMethod**********/
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<Employee> getEmployee(@PathVariable("id") long id) {
System.out.println("Fetching Employee with id " + id);
Employee user = employeeService.findById(id);
if (user == null) {
System.out.println("Employee with id " + id + " not found");
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Employee>(user, HttpStatus.OK);
}
/********This is client implementation**********/
@RequestMapping(value = "/employee/{id}", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
public ResponseEntity<Employee> getEmployee(@PathVariable("id") long id) {
System.out.println("Fetching Employee with id " + id);
Employee user = employeeService.findById(id);
if (user == null) {
System.out.println("Employee with id " + id + " not found");
return new ResponseEntity<Employee>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<Employee>(user, HttpStatus.OK);
}
/*************Done**************/
/*******Output******/
<200 OK,<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employee>
<age>33</age>
<id>1</id>
<name>Tomy</name>
<salary>70000.0</salary>
</employee>`enter code here`
,{Server=[Apache-Coyote/1.1], Access-Control-Allow-Origin=[*], Access-Control-Allow-Methods=[POST, GET, PUT, OPTIONS, DELETE], Access-Control-Max-Age=[3600], Access-Control-Allow-Headers=[x-requested-with], Content-Type=[application/xml], Transfer-Encoding=[chunked], Date=[Wed, 20 Apr 2016 12:49:16 GMT]}>