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

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.lryc.cn/news/2379560.html

相关文章:

  • Linux下Nginx源码安装步骤详解
  • SQLMesh 增量模型从入门到精通:5步实现高效数据处理
  • Zookeeper 入门(二)
  • 【架构篇】安全架构-双向认证
  • 负载均衡—会话保持技术详解
  • Flask快速入门和问答项目源码
  • go语法大赏
  • 软件工程各种图总结
  • R-tree详解
  • AAAI2024 | 基于特征多样性对抗扰动攻击 Transformer 模型
  • 关于数据湖和数据仓的一些概念
  • 鸿蒙OSUniApp制作自定义的下拉菜单组件(鸿蒙系统适配版)#三方框架 #Uniapp
  • C++面试2——C与C++的关系
  • 常用的Java工具库
  • 基于LabVIEW的双音多频系统设计
  • R S的EMI接收机面板
  • [ctfshow web入门] web122
  • Nginx+Lua 实战避坑:从模块加载失败到版本冲突的深度剖析
  • LangChain框架-Chain 链详解
  • Java虚拟机 - JVM与Java体系结构
  • elementUI调整滚动条高度后与固定列冲突问题解决
  • 基于 nvitop+Prometheus+Grafana 的物理资源与 VLLM 引擎服务监控方案
  • 互联网大厂Java求职面试:Spring AI与大模型交互在短视频平台中的应用
  • 【Lua】java 调用redis执行 lua脚本
  • 【工奥阀门科技有限公司】签约智橙PLM
  • 灌区量测水自动化监测解决方案
  • SpringBoot整合MQTT实战:基于EMQX构建高可靠物联网通信,从零到一实现设备云端双向对话
  • AI与机器学习深度集成:从设备端能力爆发到开发工具智能化
  • 界面控件DevExpress WinForms v24.2 - 数据处理功能增强
  • Linux的MySQL头文件和找不到头文件问题解决