Spring 集成带有 header 个参数的 Http OutboundGateway PUT

Spring Integration Http OutboundGateway PUT with header parameters

我正在尝试在远程 REST 端点上进行 PUT,我需要为其提供凭据作为 headers 的一部分,但到目前为止没有成功。

方法一:

    @Bean
    public IntegrationFlow outboundGateway() {
        return flow -> flow
                .transform(transformer)
                .enrichHeaders(h -> h.header("x-api-key", "secret123")
                                     .header("contentType", MediaType.APPLICATION_JSON))
                .handle(Http.outboundGateway("https://remote-service.com/car")
                        .mappedRequestHeaders()
                .httpMethod(HttpMethod.PUT)
                .expectedResponseType(String.class))
                .log();
    }

我一直收到 403 Forbidden。

我很容易用 RestTemplate 实现了同样的效果:

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(getHeaders());
restTemplate.put("https://remote-service.com/car", request);
...

    private HttpHeaders getHeaders() {
        HttpHeaders headers = new HttpHeaders();
        headers.add("x-api-key", "secret123");
        return headers;
    }

如何使用 Http OutboundGateway 发送此 x-api-key header 及其值?

谢谢。

x-api-key不是标准的http header,所以你需要把它转过来:

 .mappedRequestHeaders(*)

为了你的Http.outboundGateway().

有关详细信息,请参阅文档:https://docs.spring.io/spring-integration/docs/5.2.6.RELEASE/reference/html/http.html#http-header-mapping