如何使用 Spring WebClient 禁用 cookie [英] How to disable cookies with Spring WebClient

查看:66
本文介绍了如何使用 Spring WebClient 禁用 cookie的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有谁知道是否有办法使用 Reactor Netty HttpClient 在 Spring WebClient 中禁用 cookie 管理?

Does anyone know if there's a way to disable cookie management in Spring WebClient using Reactor Netty HttpClient?

我注意到 WebClient.BuilderHttpClient API 提供了一种将 cookie 添加到出站请求的方法,但我正在寻找一种方法来完全禁止它们(如果存在).这类似于 Apache 的 HttpComponentClientBuilder.

I noticed both WebClient.Builder and HttpClient APIs provide a means to add cookies to an outbound request but I am looking for a way to inhibit them altogether if such exists. That is akin to disableCookieManagement on Apache's HttpComponentClientBuilder.

推荐答案

看起来没有办法禁用 cookie 处理本身,但这似乎有效:创建自己的 HttpClient,然后使用 HttpClient.doOnRequest 注册回调在发送请求之前调用.在回调中,调用 HttpClientRequest.requestHeaders() 获取请求头,然后删除 Cookie 头.

It looks like there's no way to disable the cookie handling per se but this seems to work: Create your own HttpClient, then use HttpClient.doOnRequest to register a callback to be called before sending the request. In the callback, call HttpClientRequest.requestHeaders() to retrieve the request headers, then delete the Cookie header.

在发送请求之前删除 User-Agent 标头的示例代码.

Sample code that removes User-Agent header before sending the request.

public class Main {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClient.create().doOnRequest((request, connection) -> {
           request.requestHeaders().remove("User-Agent");
        });
        WebClient client = WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
        Mono<String> r = client.get().uri("https://www.google.com").retrieve()
                .bodyToMono(String.class);
        System.out.println(r.block());
    }
}

这篇关于如何使用 Spring WebClient 禁用 cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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