我想使用拦截器为通过rest模板发出的每个请求添加授权标头。我是这样做的:
{
"Type": "AWS::EC2::Instance",
"Properties": {
"BlockDeviceMappings": [
{
"DeviceName": "/dev/sda1",
"Ebs" : { "SnapshotId" : {"Ref": "Snapshot1Id"} }
},
{
"DeviceName": "/dev/sda2",
"Ebs" : { "SnapshotId" : {"Ref": "Snapshot2Id"} }
},
{
"DeviceName": "/dev/sda3",
"Ebs" : { "SnapshotId" : {"Ref": "Snapshot3Id"} }
}
],
"ImageId": { "Ref": "InstanceAmi" }
}
但是当我这样做时
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();
}
没有调用拦截器(Iv在其中放置了断点并且没有触发)。发出请求并返回明显丢失的auth key响应。为什么我的拦截器没有被调用?
答案 0 :(得分:3)
好的我知道发生了什么事。在检查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();
}