我正在使用Spring RestTemplate编写客户端REST GET调用。我需要将http标头传递给GET调用。
请找到代码段:
String url = "http://<hostname>:7001/api?id=231";
ResponseEntity<ResponseObject> getEntity = this.restTemplate.getForEntity(url, ResponseObject.class);
return getEntity .getBody();
org.springframework.http.HttpHeaders headers = new org.springframework.http.HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");
我需要在此REST get调用中传递诸如Accept和username这样的标头。 同样需要哪些代码更改,以便我可以在RestTemplate中传递标头。
答案 0 :(得分:0)
将您的代码用作:
org.springframework.http.HttpHeaders headers = new
org.springframework.http.HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");
String url = "http://<hostname>:7001/api?id=231";
ResponseEntity<ResponseObject> getEntity =
this.restTemplate.exchange(url,HttpMethod.GET,new HttpEntity<>( headers),ResponseObject.class);
return getEntity .getBody();
答案 1 :(得分:0)
getForEntity
不支持设置标题。请改用exchange
:
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", "application/xml");
headers.set("username", "ABC");
HttpEntity entity = new HttpEntity(headers);
ResponseEntity<ResponseObject> response = restTemplate.exchange(
url, HttpMethod.GET, entity,ResponseObject.class);
答案 2 :(得分:0)
通用休息模板执行器方法:
public <T, E extends TIBCOResponse> E executeRequest(HttpMethod method,
HttpHeaders httpHeaders,
String url,
T requestBody,
Map<String, String> paramters,
Class<E> clazz) {
HttpEntity<T> entity = new HttpEntity<>(requestBody, httpHeaders);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<E> response = restTemplate.exchange(url, method, entity, clazz, paramters);
return response.getBody();
}
服务方法实施:
public ResponseObject FuncCallerInsideRest(IntegrationDTO integrationDTO) {
String OPERATION_URL = "/FindAccountInfo?accountNumber="+integrationDTO.getAccountNumber();
Map<String, String> parameters = new HashMap<>();
httpHeaders = new HttpHeaders();
httpHeaders.set("RetryLimit", "2");
httpHeaders.set("Authorization", "abcd");
httpHeaders.set("SessionID", integrationDTO.getSessionID());
ResponseObject ResponseObject = this.executeRequest(HttpMethod.GET, httpHeaders,
BASE_URL.concat(PATH_URL.concat(OPERATION_URL)), null, parameters,
ResponseObject.class);
return ResponseObject;
}