如何将请求属性添加到 WebTestClient / WebClient?

How to add request attributes to a WebTestClient / WebClient?

我环顾四周,但似乎没有合适的解决方案来解决我并不孤单的问题:为什么我无法向 WebClient(或分别是 WebTestClient)请求添加属性? 每当我尝试这样的事情时:

var respSpec = webTestClient.post()
        .uri("http://localhost:10080" + "/endpoint")
        .header(apiSecretHeader, secret)
        .header("HEADER_1", "header value 1")
        .header("HEADER_2", "header value 2")
        .attribute("requestId",  UUID.randomUUID().toString())
        .attribute("aUrl", theUrl)   // private URL theUrl;
  //    .attributes(m())
        .exchange();

我收到错误请求 (400) 作为响应。尝试使用 .attributes 而不是 .attribute 也会导致 400。

REST 控制器端点:

@PostMapping(value = "/endpoint", produces = {MediaType.APPLICATION_JSON_VALUE})
    @ResponseStatus(HttpStatus.ACCEPTED)
    public ResponseEntity<?> triggerAction(@RequestAttribute final HttpHeaders httpHeaders, @RequestAttribute final String requestId, @NonNull @RequestAttribute(value = "myActionUrl") final URL myActionUrl) {
    ...
}

控制台输出:

2021-11-19 09:06:08.050 ERROR [main] [] [] [VNB_REST_OUTBOUND_ADAPTER] [system] [Initiale Log Konfiguration] o.s.t.w.r.server.ExchangeResult:231 - Request details for assertion failure:

> POST http://localhost:10080/endpoint
> WebTestClient-Request-Id: [1]
> X-SECRET: [secret]
> HEADER1: [header value 1]
> HEADER2: [header value 2]

No content

< 400 BAD_REQUEST Bad Request
< Content-Type: [application/json]
< Transfer-Encoding: [chunked]
< Date: [Fri, 19 Nov 2021 09:06:07 GMT]
< Connection: [close]

{
  "timestamp" : "2021-11-19T09:06:07.963+00:00",
  "status" : 400,
  "error" : "Bad Request",
  "path" : "/endpoint"
}
 

java.lang.AssertionError: Status expected:<204 NO_CONTENT> but was:<400 BAD_REQUEST>
Expected :204 NO_CONTENT
Actual   :400 BAD_REQUEST

你可以看到我尝试添加的属性似乎没有被考虑

假设您在谈论请求参数,最简单的方法是使用 WebClient.Builder,如下所示:

var uriTemplate = "http://localhost:10080/endpoint?requestId={requestId}&aUrl={aUrl}";
var respSpec = webClientBuilder.baseUr(uriTemplate).build()
      .post()
      .uri( uri -> uri.build(UUID.randomUUID(), theUrl) )
      .header(apiSecretHeader, secret)
      .header("HEADER_1", "header value 1")
      .header("HEADER_2", "header value 2")
      .exchange();

如果您不想使用 URI 模板,则需要按如下方式指定 URI 中的所有内容:

var respSpec = webTestClient.post()
      .uri( uriBuilder - > uriBuilder
        .scheme("http")
        .host("localhost")
        .port("10080")
        .path("/endpoint")
        .queryParam("requestId", requestId)
        .queryParam("aUrl", aUrl)
        .build())
      .header(apiSecretHeader, secret)
      .header("HEADER_1", "header value 1")
      .header("HEADER_2", "header value 2")
      .exchange();