我使用Spring模板来调用外部的公共REST。作为API身份验证的一部分,我需要在报头中发送用户密钥。我不知道如何在Spring模板GET调用中设置自定义header属性。
RestTemplate restTemplate = new RestTemplate();
<Class> object = restTemplate.getForObject("<url>","<class type>");我发现可以通过设置set("key“、"value")来实现HttpHeaders类,但没有找到任何具体的示例。如果你有什么消息告诉我。
发布于 2018-02-19 18:04:45
要通过请求头在REST请求中传递自定义属性,我们需要创建一个新的HTTPHeaders对象,并通过set方法设置键和值,并将其传递给HttpEntity,如下所示。
接下来,RestTemplate ()方法可以是具有HttpEntity方法param的方法。
HttpHeaders headers = new HttpHeaders();
headers.set("custom-header-key","custom-header-value");
HttpEntity<String> entity = new HttpEntity<>("paramters",headers);
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<ResponseObj> responseObj = restTemplate.exchange("<end point url>", HttpMethod.GET,entity,ResponseObj.class);
ResponseObj resObj = responseObj.getBody();发布于 2018-02-17 06:17:55
试试像这样的东西
HttpHeaders createHeaders(String username, String password){
return new HttpHeaders() {{
String auth = username + ":" + password;
byte[] encodedAuth = Base64.encodeBase64(
auth.getBytes(Charset.forName("US-ASCII")) );
String authHeader = "Basic " + new String( encodedAuth );
set( "Authorization", authHeader );
}};
}我希望它能帮助你:)
https://stackoverflow.com/questions/48838435
复制相似问题