java 在@HttpExchange中添加动态标头

kmpatx3s  于 2023-02-14  发布在  Java
关注(0)|答案(1)|浏览(652)

我正在探索Spring Boot 3。我创建了2个REST服务,其中一个服务与另一个服务通信。两者都使用Spring-starter-web,也导入了Webflux。我发现我们可以使用*@HttpExchange *(我以前的经验是Spring Boot 2.6,也只使用RestClient)。我已经按照this link进行了尝试。
我也添加了@HttpExchange. Created * HttpServiceProxyFactory * bean。下面是我的代码。如何动态传递自定义头?假设我想在头中传递经过验证的用户数据或其他一些要动态设置的值。

    • 客户**
@HttpExchange("/blog")
public interface BlogClient {

    @PostExchange
    Mono<Course> create(@RequestBody BlogInfo blogInfo);
    
    @GetExchange
    Mono<Course> get(@PathVariable Long id);
}
    • 配置**
WebClient webClient(String url) {
    return WebClient.builder().baseUrl(url).build();
}

@Bean
BlogClient blogClient() {
    
    HttpServiceProxyFactory httpServiceProxyFactory = HttpServiceProxyFactory
            .builder(WebClientAdapter.forClient(webClient(blogBaseURL))).build();
    return httpServiceProxyFactory.createClient(BlogClient.class);

}
    • 更新**

我发现我们可以添加*@RequestHeader * 作为参数,并传递header. Similar to reading headers。但这样一来,需要在所有交换接口的所有方法中添加该参数,这似乎太多了。

@PostExchange
Mono<Course> create(@RequestBody BlogInfo blogInfo, @RequestHeader Map<String, String> headers);
        
@GetExchange
Mono<Course> get(@PathVariable Long id, @RequestHeader Map<String, String> headers);
fnx2tebb

fnx2tebb1#

您可以使用WebClient.RequestHeadersSpec接口在发送请求之前修改标头,修改webClient方法以接受自定义标头作为参数,然后将它们传递给WebClient.RequestHeadersSpec接口:
类似于:

WebClient webClient(String url, Map<String, String> headers) {
return WebClient.builder().baseUrl(url).defaultHeaders(h -> headers.forEach(h::add)).build();
}

@Bean
BlogClient blogClient() {

HttpServiceProxyFactory httpServiceProxyFactory = HttpServiceProxyFactory
        .builder(WebClientAdapter.forClient(webClient(blogBaseURL, new HashMap<>()))).build();
return httpServiceProxyFactory.createClient(BlogClient.class);

}

相关问题