使用WebClient发请求

获取WebClient对象

WebClient webClient = WebClient.builder()
        .baseUrl("http://jsonplaceholder.typicode.com")
        .defaultHeader(HttpHeaders.USER_AGENT,"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)")
        .defaultCookie("ACCESS_TOKEN", "test_token")
        .build();

发送请求

Mono<String> mono = webClient
                .get() //请求方式
                .uri("/posts/1")  //请求路径
                .headers(headersConsumer)//设置请求头
                .retrieve() //获取响应体
                .bodyToMono(String.class); //响应数据类型转换,可以直接转成自定义Bean
//				.bodyToFlux(PostBean.class); //转成Bean数组
//		        List posts = flux.collectList().block();
        System.out.println(mono.block());//响应体数据

header和cookie的设置可以通过实现Consumer接口传集合

Consumer<HttpHeaders> headersConsumer = httpHeaders -> {
            for (Map.Entry<String, String> entry : headersMap.entrySet()) {
                httpHeaders.add(entry.getKey(), entry.getValue());
            }
        };

uri装载参数

.uri("/{1}/{2}", "posts", "1")

String type = "posts";
int id = 1;
.uri("/{type}/{id}", type, id)
    
Map<String,Object> map = new HashMap<>();
map.put("type", "posts");
map.put("id", 1);
.uri("/{type}/{id}", map)

非阻塞式获取相应(异步获取结果)

mono.subscribe(result -> {
            System.out.println(result);
        });

post发json

.contentType(MediaType.APPLICATION_JSON_UTF8)//设类型

.body(BodyInserters.fromObject(jsonStr))//传json字符串
.syncBody(postBean)//传bean

post传表单

.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.body(BodyInserters.fromFormData(map))

更多可以看https://blog.csdn.net/weixin_35688430/article/details/119750922

@LoadBalanced

加在builder的注册上

@Bean
@LoadBalanced
public WebClient.Builder builder(){
    return WebClient.builder();
}

你可能感兴趣的:(Spring,java,spring,boot,spring,后端)