我正在使用 org.springframework.http.HttpHeaders 来保存我的标头。我收到来自服务的请求,将请求中的标头收集到 HttpHeaders 中,然后我想使用这些相同的标头发出新请求。我不知道会有什么或有多少标头(我至少会添加几个自定义标头)。我想使用 Spring Boot 3.2 的新 RestClient。
我知道我可以用
.header(key, value)
输入它们,但我不知道我会有多少个标题。我可以使用.headers(Consumer<HttpHeaders>)
吗?我该如何使用它?我尝试循环遍历我的标头来添加它们,但是当我尝试发送我的请求时,它会超时。
return restClient.post()
.uri(new URI(endpoint))
.body(bodyStr)
.headers(/*how?*/)
.retrieve()
.body(MyClass.class);
我试过这个:
return restClient.post()
.uri(new URI(endpoint))
.body(body)
.headers(headers -> headers.addAll(httpHeaders))
.retrieve()
.body(MyClass.class);
但这会超时。
您可以利用
defaultHeaders(...)
提供的 RestClient
。下面是示例代码片段,您可以在配置类中使用 create RestClient
bean。
RestClient.builder()
.baseUrl("your_url_here")
.defaultHeaders(
httpHeaders -> {
httpHeaders.setBasicAuth("your_username", "your_password");
httpHeaders.set("Content-Type", "application/json");
httpHeaders.set("custom_header_1", "custom_value");
httpHeaders.set("custom_header_2", "custom_value");
})
.build();
此外,您可以添加任意数量的标题。如果您有动态标头,那么您可以在进行任何 REST 调用之前构造标头。
但是,我不清楚您担心的是超时。当您尝试进行 POST 调用并且没有超时构建标头时,您可能会遇到超时。这对我来说没有意义。如果您的 REST 调用超时,您可以随时更改设置为 120 秒的默认超时。