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

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.dtcms.com/a/198194.html

相关文章:

  • 【Spring】Spring中的适配器模式
  • 【PRB】深度解析GaN中最浅的受主缺陷
  • go语言协程调度器 GPM 模型
  • Vue-监听属性
  • 理想AI Talk第二季-重点信息总结
  • 【ROS2】RViz2源码分析(九):RosClientAbstraction和RosNodeAbstraction的关系
  • ngx_http_realip_module 模块概述
  • 【DeepSeek论文精读】11. 洞察 DeepSeek-V3:扩展挑战和对 AI 架构硬件的思考
  • c++多线程debug
  • 符合Python风格的对象(再谈向量类)
  • Spring Web MVC————入门(3)
  • Go语言--语法基础5--基本数据类型--类型转换
  • Vue 3 中使用 md-editor-v3 的完整实例markdown文本
  • 网络编程套接字(二)
  • 高并发内存池|二、Common
  • 【JavaWeb】JDBC
  • 如何利用内网穿透实现Cursor对私有化部署大模型的跨网络访问实践
  • java中sleep()和wait()暂停线程的区别
  • [Java实战]Spring Boot整合Elasticsearch(二十六)
  • 大模型微调步骤整理
  • 第9章 组件及事件处理
  • Mac 在恢复模式下出现 旋转地球图标 但进度非常缓慢
  • Oracle 内存优化
  • java中的Servlet3.x详解
  • sparkSQL读入csv文件写入mysql
  • 10.8 LangChain三大模块深度实战:从模型交互到企业级Agent工具链全解析
  • 多模态大语言模型arxiv论文略读(八十一)
  • SuperYOLO:多模态遥感图像中的超分辨率辅助目标检测之论文阅读
  • 贪心算法应用:最大匹配问题详解
  • 算法岗实习八股整理——深度学习篇(不断更新中)