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

用spring发送http请求

在Spring中,你可以使用RestTemplateWebClient来发送HTTP请求。下面分别给出使用这两个类的简单示例。

现在pom.xml中导入依赖

<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId><version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-webflux</artifactId><version>2.6.0</version> <!-- Specify the version of Spring Boot -->
</dependency>

1. 使用 RestTemplate:

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;public class HttpRequestExample {public static void main(String[] args) {// 创建 RestTemplate 实例RestTemplate restTemplate = new RestTemplate();// 设置请求 URLString url = "https://api.example.com/data";// 发送 GET 请求,并获取响应ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);// 获取响应体String responseBody = responseEntity.getBody();// 处理响应System.out.println("Response: " + responseBody);}
}

 

2、使用 WebClient:

import org.springframework.web.reactive.function.client.WebClient;public class HttpRequestExample {public static void main(String[] args) {// 创建 WebClient 实例WebClient webClient = WebClient.create();// 设置请求 URLString url = "https://api.example.com/data";// 发送 GET 请求,并获取响应String responseBody = webClient.get().uri(url).retrieve().bodyToMono(String.class).block();// 处理响应System.out.println("Response: " + responseBody);}
}

http://www.lryc.cn/news/237758.html

相关文章:

  • 赴日开发工程师是做什么的?
  • Wireshark的数据包它来啦!
  • 接口测试需要验证数据库么?
  • 配置 `PostgreSQL` 与 `Keepalived` 以实现高可用性
  • C++: int转换成LPCSTR
  • kettle官网和中文网地址
  • 纽扣电池类产品上架亚马逊澳大利站认证标准要求AS/NZS 62368
  • 网站监控的重要性及实施策略
  • 亚马逊车灯外贸出口CE认证标准办理解析
  • windows 查看防火墙设置命令使用方法
  • [Linux版本Debian系统]安装cuda 和对应的cudnn以cuda 12.0为例
  • NextJS开发:解决React Hook useEffect has a missing dependency
  • 交叉编译tcpdump
  • 万字解析设计模式之 装饰者模式
  • 生成对抗网络Generative Adversarial Network,GAN
  • C++入门第八篇---STL模板---list的模拟实现
  • 论文导读 | 大语言模型与知识图谱复杂逻辑推理
  • 数智竞技何以成为“科技+体育”新样本?
  • Vue项目Jenkins自动化部署
  • 特效!视频里的特效在哪制作——Adobe After Effects
  • 2023年中国醇酸树脂涂料需求量、应用领域及市场规模前景分析[图]
  • 【Linux进阶之路】动静态库
  • Ubuntu磁盘扩展容量
  • 2023年中国羽绒制品需求现状、市场规模及细分产品规模分析[图]
  • 动手学深度学习——循环神经网络的从零开始实现(原理解释+代码详解)
  • 【操作系统】文件系统的逻辑结构与目录结构
  • 局域网内Ubuntu上搭建Git服务器
  • 基础课10——自然语言生成
  • xpath
  • Java拼图小游戏