SpringBoot項目里面發(fā)起http請求的幾種方法
在Spring Boot項目中,有幾種常用的方式可以發(fā)起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+推薦的響應(yīng)式方式)
// 需要添加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+內(nèi)置)
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();
// 發(fā)送請求
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();
// 發(fā)送請求
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");
// 發(fā)送請求
CloseableHttpResponse response = httpClient.execute(httpPost);
選擇建議
- 對于新項目,推薦使用 WebClient (響應(yīng)式) 或 HttpClient (Java內(nèi)置)
- 如果使用Spring Cloud,Feign Client 是一個很好的選擇
- RestTemplate 雖然仍可使用,但已進(jìn)入維護(hù)模式,不推薦新項目使用
- 需要更多控制時,可以考慮 OkHttp 或 Apache HttpClient
到此這篇關(guān)于SpringBoot項目里面發(fā)起http請求的幾種方法的文章就介紹到這了,更多相關(guān)SpringBoot發(fā)起http請求內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
SpringBoot中優(yōu)化if-else語句的七種方法
if-else語句是控制流程的基本工具,但過度使用會使代碼變得復(fù)雜且難以維護(hù),在SpringBoot , SpringCloud項目中,優(yōu)化if-else結(jié)構(gòu)變得尤為重要,本文將深入探討七種策略,旨在減少SpringBoot , SpringCloud項目中 if-else的使用,需要的朋友可以參考下2024-07-07
MyBatis使用<foreach>標(biāo)簽like查詢報錯解決問題
這篇文章主要介紹了MyBatis使用<foreach>標(biāo)簽like查詢報錯解決問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03
教你使用idea搭建ssm詳細(xì)教程(Spring+Spring Mvc+Mybatis)
今天教大家使用idea搭建ssm詳細(xì)教程(Spring+Spring Mvc+Mybatis),文中有非常詳細(xì)的圖文介紹及代碼示例,對正在學(xué)習(xí)使用idea的小伙伴很有幫助,需要的朋友可以參考下2021-05-05
Java中SimpleDateFormat方法超詳細(xì)分析
這篇文章主要給大家介紹了關(guān)于Java中SimpleDateFormat方法超詳細(xì)分析的相關(guān)資料,SimpleDateFormat 是一個以國別敏感的方式格式化和分析數(shù)據(jù)的具體類,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-08-08
SpringCloud與Consul集成實現(xiàn)負(fù)載均衡功能
負(fù)載均衡基本概念有:實服務(wù)、實服務(wù)組、虛服務(wù)、調(diào)度算法、持續(xù)性等,其常用應(yīng)用場景主要是服務(wù)器負(fù)載均衡,鏈路負(fù)載均衡。這篇文章主要介紹了SpringCloud與Consul集成實現(xiàn)負(fù)載均衡 ,需要的朋友可以參考下2018-09-09
IDEA 2020.3 更新了機器學(xué)習(xí)都整上了
IDEA 歡迎窗口全新升級,首頁增加三個選項卡,一個用于設(shè)置 IDE 界面的 Customize,一個用于插件安裝的 Plugins,一個于訪問幫助和學(xué)習(xí)資源的 Learn IntelliJ IDEA,另外包括之前用于管理項目的 Projects,需要的朋友可以參考下2020-12-12
Springboot項目實現(xiàn)Mysql多數(shù)據(jù)源切換的完整實例
這篇文章主要給大家介紹了關(guān)于Springboot項目實現(xiàn)Mysql多數(shù)據(jù)源切換的完整實例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-11-11

