在Spring RestTemplate GET调用上设置自定义标头

问题描述 投票:1回答:2

我使用Spring REST Template来调用外部公共REST API。作为API身份验证的一部分,我需要在标头中发送用户密钥。我不知道如何在Spring REST模板GET调用中设置自定义头属性。

RestTemplate restTemplate = new RestTemplate();
<Class> object = restTemplate.getForObject("<url>","<class type>");

我发现这可以通过设置set(“key”,“value”)来完成HttpHeaders类,但没有找到任何具体的例子。如果您有任何信息,请告诉我。

resttemplate spring-rest
2个回答
3
投票

要通过请求Header在REST请求中传递自定义属性,我们需要创建一个新的HTTPHeaders对象,并通过set方法设置键和值,并传递给HttpEntity,如下所示。

接下来RestTemplate,exchange()方法可以有一个HttpEntity的方法参数。

 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();

1
投票

尝试这样的事情

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 );

    }};

}

我希望它能帮到你:)

© www.soinside.com 2019 - 2024. All rights reserved.