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

Setting custom header on Spring RestTemplate GET call

我正在使用 Spring REST 模板调用外部 public REST API。作为 API 身份验证的一部分,我需要在 header 中发送 user-key。我不确定如何在 Spring REST 模板 GET 调用中设置自定义 header 属性。

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

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

尝试这样的事情

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

    }};

}

希望对你有所帮助:)

要通过请求头在 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();