WebClient 快速入门 (使用 WebClient 发起 HTTP 请求)

发布于:2024-06-06 ⋅ 阅读:(157) ⋅ 点赞:(0)

1.简介

  1. 执行异步 HTTP 请求WebClient 允许你发送 GET、POST、PUT、DELETE 等各种 HTTP 请求,并且这些请求都是异步的,不会阻塞调用线程。

  2. 处理响应:你可以使用 WebClient 来处理 HTTP 响应,包括获取响应体、响应头和状态码等信息。

  3. 请求和响应的编解码WebClient 支持自动编解码请求体和响应体,可以轻松地处理 JSON、XML 等格式的数据。

  4. 错误处理WebClient 提供了丰富的错误处理机制,可以处理各种 HTTP 相关的错误。

  5. 过滤器链和请求修改WebClient 允许你添加过滤器来修改或处理请求和响应,例如添加通用头信息、日志记录、请求重试等。

  6. 性能优化:由于 WebClient 是非阻塞的,它可以显著提高应用程序的性能,特别是在处理大量并发请求时。

  7. 响应式编程WebClient 返回的是反应式类型(如 Mono 或 Flux),这使得它可以很好地与反应式编程模型和其他反应式组件(如反应式数据库)集成。

  8. 测试WebClient 可以用于自动化测试,模拟 HTTP 请求和响应,以便测试应用程序的各个部分。

2.引入依赖

        <!-- wbeClient-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-webflux</artifactId>
        </dependency>

3.配置类WebClientConfig

baseUrl可以根据发起请求的路径的进行修改

package com.eco.thirdparty.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.reactive.function.client.WebClient;

@Configuration
public class WebClientConfig {

    @Bean
    public WebClient webClient(WebClient.Builder builder) {
        return builder
                .baseUrl("")
                .defaultHeader("Content-Type", "application/json")
                .defaultHeader("Accept", "application/json")
                .build();
    }
}

4.具体代码:(以post发起携参请求获取数据为例)

Controller:

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

   private final IUserService userService;

   @PostMapping("/sendWebClientRequest")
   public Result sendWebClientRequest(){
      Object sendWebClientRequest = userService.sendWebClientRequest();

     return Result.success(sendWebClientRequest);
   }
   
}

Service:

public interface IUserService extends IService<User> {

    Object sendWebClientRequest();

}

ServiceImpl:

注意:如果在配置类中写了baseUrl那么此时相当于的webClient.uti(baseUrl + requestPath)

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements IUserService {

    private final WebClient webClient;

    @Override
    public Object sendWebClientRequest() {
        //发送请求的url
        String requestPath = "http://localhost:8881/user/query";

        UserQuery userQuery = new UserQuery();
        userQuery.setGender(1);

        // 使用 block() 同步等待响应
        Mono<Object> responseMono = webClient
                .post()
                .uri(requestPath)
                .bodyValue(userQuery)
                .retrieve()
                .bodyToMono(Object.class);

        // 使用 block() 获取响应值
        Object resultJson = responseMono.block();

        // 如果需要,可以在这里处理 resultJson
        System.out.println("Received data: " + resultJson);

        return resultJson;
    }
}


网站公告

今日签到

点亮在社区的每一天
去签到