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

SpringBoot项目里面发起http请求的几种方法

在Spring Boot项目中发起HTTP请求的方法

在Spring Boot项目中,有几种常用的方式可以发起HTTP请求,以下是主要的几种方法:

1. 使用RestTemplate (Spring 5之前的主流方式)

// 需要先注入RestTemplate
@Autowired
private RestTemplate restTemplate;public void makeRequest() {// GET请求ResponseEntity<String> response = restTemplate.getForEntity("https://api.example.com/data", String.class);// POST请求HttpHeaders headers = new HttpHeaders();headers.setContentType(MediaType.APPLICATION_JSON);HttpEntity<String> request = new HttpEntity<>("{\"key\":\"value\"}", headers);ResponseEntity<String> response = restTemplate.postForEntity("https://api.example.com/data", request, String.class);
}

2. 使用WebClient (Spring 5+推荐的响应式方式)

// 需要添加spring-boot-starter-webflux依赖
WebClient webClient = WebClient.create();// GET请求
Mono<String> response = webClient.get().uri("https://api.example.com/data").retrieve().bodyToMono(String.class);// POST请求
Mono<String> response = webClient.post().uri("https://api.example.com/data").contentType(MediaType.APPLICATION_JSON).bodyValue("{\"key\":\"value\"}").retrieve().bodyToMono(String.class);

3. 使用HttpClient (Java 11+内置)

HttpClient client = HttpClient.newHttpClient();// GET请求
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.example.com/data")).build();// POST请求
HttpRequest request = HttpRequest.newBuilder().uri(URI.create("https://api.example.com/data")).header("Content-Type", "application/json").POST(HttpRequest.BodyPublishers.ofString("{\"key\":\"value\"}")).build();// 发送请求
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

4. 使用Feign Client (声明式REST客户端)

// 需要添加spring-cloud-starter-openfeign依赖
@FeignClient(name = "exampleClient", url = "https://api.example.com")
public interface ExampleClient {@GetMapping("/data")String getData();@PostMapping("/data")String postData(@RequestBody String body);
}// 使用
@Autowired
private ExampleClient exampleClient;public void makeRequest() {String response = exampleClient.getData();
}

5. 使用第三方库如OkHttp或Apache HttpClient

OkHttp示例:

OkHttpClient client = new OkHttpClient();// GET请求
Request request = new Request.Builder().url("https://api.example.com/data").build();// POST请求
RequestBody body = RequestBody.create("{\"key\":\"value\"}", MediaType.parse("application/json"));
Request request = new Request.Builder().url("https://api.example.com/data").post(body).build();// 发送请求
Response response = client.newCall(request).execute();

Apache HttpClient示例:

CloseableHttpClient httpClient = HttpClients.createDefault();// GET请求
HttpGet httpGet = new HttpGet("https://api.example.com/data");// POST请求
HttpPost httpPost = new HttpPost("https://api.example.com/data");
StringEntity entity = new StringEntity("{\"key\":\"value\"}");
httpPost.setEntity(entity);
httpPost.setHeader("Content-type", "application/json");// 发送请求
CloseableHttpResponse response = httpClient.execute(httpPost);

选择建议

  • 对于新项目,推荐使用 WebClient (响应式) 或 HttpClient (Java内置)
  • 如果使用Spring Cloud,Feign Client 是一个很好的选择
  • RestTemplate 虽然仍可使用,但已进入维护模式,不推荐新项目使用
  • 需要更多控制时,可以考虑 OkHttpApache HttpClient
http://www.xdnf.cn/news/7028.html

相关文章:

  • EMQX开源版安装指南:Linux/Windows全攻略
  • 连续概率分布 (拉普拉斯分布)
  • Flink 的水印机制
  • 第三十七节:视频处理-视频读取与处理
  • PostGIS实现矢量数据转栅格数据【ST_AsRaster】
  • FFmpeg:多媒体处理的终极利器
  • 有哪些GIF图片转换的开源工具
  • Neo4j数据库
  • spark数据处理练习题详解【上】
  • 【AGI】大模型微调数据集准备
  • leetcodehot100刷题——排序算法总结
  • ubuntu18.04通过cuda_11.3_xxx.run安装失败,电脑黑屏解决办法
  • FastDFS分布式文件系统架构学习(一)
  • 给个人程序加上MCP翅膀
  • React Flow 边事件处理实战:鼠标事件、键盘操作及连接规则设置(附完整代码)
  • 数据脱敏-6种方案,你选哪种?
  • web系统安全管理
  • Ubuntu22.04开机运行程序
  • ubuntu 安装mq
  • JUC入门(一)
  • 【MYSQL】笔记
  • 多用途商务,电子产品发布,科技架构,智能手表交互等发布PPT模版20套一组分享
  • C++函数基础:定义与调用函数,参数传递(值传递、引用传递)详解
  • JAVA SE 多线程(上)
  • Linux编译rpm包与deb包
  • ACL完全解析:从权限管理到网络安全的核心防线
  • 股票数据源对接技术指南:印度尼西亚、印度、韩国
  • 【PostgreSQL系列】PostgreSQL 复制参数详解
  • 架构思维:构建高并发扣减服务_分布式无主架构
  • Android开发——原生渲染方案实现 PDF 预览功能