2017-10-20 108 views
0

我想使用攔截器爲每個通過rest模板創建的請求添加授權頭。我這樣做是這樣的:爲什麼我的RestTemplate ClientHttpRequestInterceptor沒有被調用?

public FirebaseCloudMessagingRestTemplate(@Autowired RestTemplateBuilder builder, @Value("fcm.server-key") String serverKey) { 
    builder.additionalInterceptors(new ClientHttpRequestInterceptor() { 
     @Override 
     public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { 
      request.getHeaders().add("Authorization", "key=" + serverKey); 
      System.out.println(request.getHeaders()); 
      return execution.execute(request, body); 
     } 
    }); 
    this.restTemplate = builder.build(); 
} 

然而,當我這樣做

DownstreamHttpMessageResponse response = restTemplate.postForObject(SEND_ENDPOINT, request, DownstreamHttpMessageResponse.class); 

攔截不叫(四把斷點它,它不火)。發出請求並返回明顯缺少授權密鑰響應。爲什麼我的攔截器不被調用?

回答

0

好吧,我知道最新情況。在檢查build()實施後,我發現RestTemplateBuilder在調用additionalInterceptors時沒有改變自我狀態,但返回給定攔截器的新構建器。鏈接調用解決了這個問題。

public FirebaseCloudMessagingRestTemplate(final @Autowired RestTemplateBuilder builder, final @Value("${fcm.server-key}") String serverKey) { 
    this.restTemplate = builder.additionalInterceptors((request, body, execution) -> { 
     request.getHeaders().add("Authorization", "key=" + serverKey); 
     log.debug("Adding authorization header"); 
     return execution.execute(request, body); 
    }).build(); 
} 
相關問題