如何在 Spring WebClient 请求之间保存 cookie?

Ben*_*Ben 5 spring spring-boot spring-webflux spring-webclient

我想在我的项目中使用 Spring Boot WebClient 来访问 REST-API。第一个请求执行 REST-API 登录并接收 cookie 作为响应。此 cookie 用作所有其他请求的“API 令牌”。

然而,WebClient似乎不存储cookie。我必须自己做吗?如果是这样,最好的方法是什么?

以下是我的示例源代码。第二个请求不使用第一个请求的 cookie。

// ### 1. API-Call to get the cookie ###
ClientResponse clientResponse = webClient
        .get()
        .uri("/api/")
        .headers(headers -> headers.setBasicAuth(user,passwd)
        .exchange()
        .block();

// ### Debug Cookie ###
if (clientResponse.statusCode().is2xxSuccessful()) {
    for (String key : clientResponse.cookies().keySet()) {
        LOG.debug("key:" + key + " value: " + clientResponse.cookies().get(key).get(0).getValue() );
    }
}   

// ### 2.API-Call (with cookie) ###
webClient
    .get()
    .uri("/api/document/4711")
    .retrieve()
    .onStatus(HttpStatus::is2xxSuccessful, r -> {
        for (String key : r.cookies().keySet()) {
            LOG.debug("key:" + r.cookies().get(key).get(0).getValue());
        }
        return Mono.empty();
    })
    .onStatus(HttpStatus::is4xxClientError, r -> {
        System.out.println("2 4xx error");
        for (String key : r.cookies().keySet()) {
            LOG.debug("key:" + r.cookies().get(key).get(0).getValue());
        }
        return Mono.error(new RuntimeException("" + r.statusCode().value()));
    })
    .onStatus(HttpStatus::is5xxServerError, response -> {
        LOG.error("2 5xx error");
        return Mono.error(new RuntimeException("5xx"));
    })
    .bodyToMono(String.class)
    .block();
Run Code Online (Sandbox Code Playgroud)

Ben*_*Ben 3

为了存储 cookie,我们更改为 Jetty HttpClient (org.eclipse.jetty.client.HttpClient)。

有关如何启用它的信息,请参阅此答案:How to use the Spring WebClient with Jetty, instead of Netty?


归档时间:

查看次数:

4037 次

最近记录:

5 年,2 月 前