如何在 Spring WebClient 中一次设置多个标头? [英] How to set multiple headers at once in Spring WebClient?

查看:76
本文介绍了如何在 Spring WebClient 中一次设置多个标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图为我的休息客户端设置标题,但每次我必须写

I was trying to set headers to my rest client but every time I have to write

webclient.get().uri("blah-blah")
         .header("key1", "value1")
         .header("key2", "value2")...

如何使用 headers() 方法同时设置所有标题?

How can I set all headers at the same time using headers() method?

推荐答案

如果这些标头在每个请求的基础上发生变化,您可以使用:

If those headers change on a per request basis, you can use:

webClient.get().uri("/resource").headers(httpHeaders -> {
    httpHeaders.setX("");
    httpHeaders.setY("");
});

这不会节省太多打字时间;因此,对于不会从一个请求更改为另一个请求的标头,您可以在构建客户端时将它们设置为默认标头:

This doesn't save much typing; so for the headers that don't change from one request to another, you can set those as default headers while building the client:

WebClient webClient = WebClient.builder().defaultHeader("...", "...").build();
WebClient webClient = WebClient.builder().defaultHeaders(httpHeaders -> {
    httpHeaders.setX("");
    httpHeaders.setY("");
}).build();

这篇关于如何在 Spring WebClient 中一次设置多个标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆