当前位置: 首页 > article >正文

使用WebClient 快速发起请求(不使用WebClientUtils工具类)

使用WebClient发起网络请求_webclient工具类-CSDN博客文章浏览阅读717次,点赞9次,收藏8次。使用WebClient发起网络请求_webclient工具类https://blog.csdn.net/qq_43544074/article/details/137044825这个是使用工具类发起的,下面就不使用工具类进行快速发起。

同样的导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-webflux -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-webflux</artifactId>
    <version>3.3.4</version>
</dependency>

然后定义初始化构建一下

    private final WebClient webClient;

    @Autowired
    public 类名_Controller(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }


    // 获取请求地址
    @Value("${dataCenter.dc2DetailUrl}")
    private String dc2DetailUrl;

    @Value("${dataCenter.prePlatformInfoUrl}")
    private String prePlatformInfoUrl;

    @Value("${dataCenter.parmsSetUrl}")
    private String parmsSetUrl;

接下来就可以进行各个方式的请求和调用处理了

GET方式:

// ==[GET]=========================================
	@ApiOperation("数据查询接口")
    @Synchronized
    @GetMapping("/data-detail")
    public Mono<AjaxResult> dataLoadDetail() throws Exception {
        // 设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("api_permanent_key", tempToken);
        return webClient.get()
                .uri(dc2DetailUrl)
                // 添加请求头
                .headers(httpHeaders -> httpHeaders.addAll(headers))
                .retrieve()
                .bodyToMono(String.class)
                .map(response -> {
                    log.info("请求数据返回响应 response = " + response);
                    try {
                        // 解析 JSON 数据
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        log.info("请求数据返回响应 jsonObject = " + jsonObject);
                        // 将处理后的数据转换为 AjaxResult 返回
                        return AjaxResult.success(jsonObject);
                    } catch (Exception e) {
                        log.error("数据处理失败: {}", e.getMessage());
                        // JSON 解析失败
                        return AjaxResult.error("数据处理失败" + e.getMessage());
                    }
                })
                .onErrorResume(e -> {
                    log.error(preCountryUrl + "GET 请求失败: {}", e.getMessage());
                    // 这里可以进行更多的日志记录或错误处理
                    return Mono.just(AjaxResult.error("GET 请求失败" + e.getMessage()));
                });
    }

有参数查询:

    @ApiOperation("查询某个类型下的个体接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "platTypeName", value = "类型名称", required = false, dataType = "String", paramType = "query", example = "电器", dataTypeClass = String.class),
            @ApiImplicitParam(name = "platTypeId", value = 类型ID", required = false, dataType = "Integer", paramType = "query", example = "5", dataTypeClass = Integer.class)
    })
    @GetMapping("/pre-platform-info")
    public Mono<AjaxResult> prePlatformInfo(
            @RequestParam(value = "platTypeName", required = false) String platTypeName,
            @RequestParam(value = "platTypeId", required = false) Integer platTypeId) {

        log.info("platTypeName = {}, platTypeId = {}", platTypeName, platTypeId);

        // 设置请求头信息
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("api_permanent_key", tempToken);

        // 构建 URI
        String uri = UriComponentsBuilder.fromHttpUrl(prePlatformInfoUrl)
                .queryParam("platTypeName", platTypeName)
                .queryParam("platTypeId", platTypeId)
                .toUriString();
        log.info("uri = {}", uri);

        return webClient.get()
                .uri(uri)
                .headers(httpHeaders -> httpHeaders.addAll(headers))
                .retrieve()
                .bodyToMono(String.class)
                .map(response -> {
                    log.info("请求数据返回响应 response = {}", response);
                    try {
                        // 解析 JSON 数据
                        JSONObject jsonObject = JSONObject.parseObject(response);
                        // 将处理后的数据转换为 AjaxResult 返回
                        return AjaxResult.success(jsonObject);
                    } catch (Exception e) {
                        log.error("JSON 解析失败", e);
                        // JSON 解析失败
                        return AjaxResult.error("数据处理失败: " + e.getMessage());
                    }
                })
                .onErrorResume(e -> {
                    log.error("GET 请求失败", e);
                    return Mono.just(AjaxResult.error("GET 请求失败: " + e.getMessage()));
                });
    }

POST方式 

	// ==[POST]=========================================
	@ApiOperation("参数设置接口")
    @PostMapping("/set-predict-time")
    public Mono<AjaxResult> setPredictTime(@RequestBody JSONObject jsonObject) throws Exception {
        // 组装请求头
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        // 组装请求体
        String requestBody = jsonObject.toJSONString();
        log.info("请求体是 " + requestBody);
        // 发送请求
        return webClient.post()
                .uri(parmsSetUrl)
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .bodyValue(requestBody) // 使用 bodyValue 直接传递请求体
                .retrieve()
                .bodyToMono(String.class)
                .flatMap(this::handleResponse) // 将响应处理逻辑提取到单独的方法中
                .onErrorResume(this::handleError); // 错误处理提取到方法中

    }


    // 处理响应
    private Mono<AjaxResult> handleResponse(String response) {
        log.info("请求数据返回响应 response = {}", response);
        try {
            // 解析 JSON 数据
            JSONObject res = JSONObject.parseObject(response);
            // 将处理后的数据转换为 AjaxResult 返回
            return Mono.just(AjaxResult.success(res.getJSONArray("rows")));
        } catch (Exception e) {
            // JSON 解析失败
            return Mono.just(AjaxResult.error("数据处理失败: " + e.getMessage()));
        }
    }

    // 错误处理
    private Mono<AjaxResult> handleError(Throwable e) {
        log.error("GET 请求失败: {}", e.getMessage(), e);
        return Mono.just(AjaxResult.error("GET 请求失败: " + e.getMessage()));
    }
	
    @ApiOperation("参数设置接口")
    @PostMapping("/set-predict-time")
    public Mono<AjaxResult> setPredictTime(@RequestBody JSONObject jsonObject) throws Exception {
        // 组装请求头
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        // 组装请求体
        String requestBody = jsonObject.toJSONString();
        log.info("请求体是 " + requestBody);
        // 发送请求
        return webClient.post()
                .uri(parmsSetUrl)
                .header(HttpHeaders.CONTENT_TYPE, "application/json")
                .bodyValue(requestBody) // 使用 bodyValue 直接传递请求体
                .retrieve()
                .bodyToMono(String.class)
                .map(response -> {
                    log.info("请求数据返回响应 response = " + response);
                    try {
                        // 解析 JSON 数据
                        JSONObject res = JSONObject.parseObject(response);
                        // 将处理后的数据转换为 AjaxResult 返回
                        return AjaxResult.success(res);
                    } catch (Exception e) {
                        // JSON 解析失败
                        return AjaxResult.error("数据处理失败" + e.getMessage());
                    }
                })
                .onErrorResume(e -> {
                    // 这里可以进行更多的日志记录或错误处理
                    return Mono.just(AjaxResult.error("POST 请求失败" + e.getMessage()));
                });
    }

至此就可以快速的发起网络请求了!


http://www.kler.cn/news/328078.html

相关文章:

  • 测试面试题:pytest断言时,数据是符点类型,如何断言?
  • 【Python|接口自动化测试】使用requests发送http请求时添加headers
  • 【LeetCode】每日一题 2024_9_27 每种字符至少取 K 个(双指针)
  • Android 安装应用-提交阶段之后剩下的操作
  • uniapp生物识别示例(人脸识别、指纹识别)
  • 【docker】docker常见命令
  • 动态分配内存
  • Gin框架简易搭建(3)--Grom与数据库
  • 归并排序【C语言版-笔记】
  • Unreal 实现建造游戏|地面交互shader
  • 06.C/C++内存管理
  • 【数据库】MongoDB 用户权限与数据之间的关系详解
  • Android studio配置AVD虚拟机
  • 【60天备战2024年11月软考高级系统架构设计师——第33天:云计算与大数据架构——大数据处理框架的应用场景】
  • 关于Java中的List<User>如何进行深拷贝
  • 贝锐蒲公英工业物联方案:助力美的智慧楼宇全球布局
  • Leetcode 611. 有效三角形的个数
  • 前端面试题(八)
  • 音视频入门基础:FLV专题(7)——Tag header简介
  • 【STM32单片机_(HAL库)】4-1【定时器TIM】定时器中断点灯实验
  • 【漏洞复现】JeecgBoot 积木报表 queryFieldBySql sql注入漏洞
  • 【进阶OpenCV】 (2)--Harris角点检测
  • 衡水中学资料大全-重构版(状元、学霸笔记)
  • .NET MAUI(.NET Multi-platform App UI)下拉选框控件
  • UE5: Content browser工具编写02
  • 【抽代复习笔记】29-群(二十三):生成子群的两道例题及子群陪集的定义
  • hdlbits系列verilog解答(Exams/m2014 q3)-77
  • 【qt】QQ仿真项目1
  • 【洛谷】P4551 最长异或路径 的题解
  • 自然语言处理的应用领域有哪些?