【问题标题】:Setting custom header on Spring RestTemplate GET call在 Spring RestTemplate GET 调用上设置自定义标头
【发布时间】:2018-02-17 06:03:50
【问题描述】:

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

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

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

【问题讨论】:

标签: resttemplate spring-rest


【解决方案1】:

要通过请求Header在REST请求中传递自定义属性,我们需要创建一个新的HTTPHeaders对象并通过set方法设置key和value并传递给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();

【讨论】:

    【解决方案2】:

    试试这样的

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

    希望对你有帮助:)

    【讨论】:

    • 其实我发现我们可以使用restTemplate.exchange方法,从body中获取response对象并转换为object。我会更新回答我的问题。
    猜你喜欢
    • 2016-11-12
    • 2018-12-18
    • 1970-01-01
    • 2013-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多