Java 調(diào)用 HTTP 接口的 7 種方式示例代碼(全網(wǎng)最全指南)
Java 調(diào)用 HTTP 接口的 7 種方式:全網(wǎng)最全指南
在開發(fā)過程中,調(diào)用 HTTP 接口是最常見的需求之一。本文將詳細(xì)介紹 Java 中 7 種主流的調(diào)用 HTTP 接口的方式,包括每種工具的優(yōu)缺點(diǎn)和完整代碼實(shí)現(xiàn)。
1. 使用 RestTemplate
RestTemplate
是 Spring 提供的同步 HTTP 客戶端,適用于傳統(tǒng)項(xiàng)目。盡管從 Spring 5 開始被標(biāo)記為過時(shí),它仍然是許多開發(fā)者的首選。
示例代碼
import org.springframework.web.client.RestTemplate; import org.springframework.http.ResponseEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpEntity; import org.springframework.http.HttpMethod; import org.springframework.http.MediaType; public class RestTemplateExample { public static void main(String[] args) { // 接口地址 String url = "https://your-api-url.com/target-method"; // 設(shè)置請(qǐng)求頭 HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); headers.add("appId", "yourAppId"); headers.add("timestamp", "yourTimestamp"); headers.add("random", "yourRandom"); headers.add("msgDigest", "yourMsgDigest"); // 設(shè)置請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 構(gòu)造請(qǐng)求 RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> entity = new HttpEntity<>(requestBody, headers); // 發(fā)送請(qǐng)求 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); // 輸出響應(yīng)結(jié)果 System.out.println("Response: " + response.getBody()); } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 簡(jiǎn)單易用,適合快速開發(fā)。
- 缺點(diǎn): 已過時(shí),不推薦用于新項(xiàng)目。
2. 使用 WebClient
WebClient
是 Spring 5 引入的現(xiàn)代化 HTTP 客戶端,支持同步和異步調(diào)用。
示例代碼
import org.springframework.web.reactive.function.client.WebClient; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; public class WebClientExample { public static void main(String[] args) { // 創(chuàng)建 WebClient WebClient webClient = WebClient.builder() .baseUrl("https://your-api-url.com") .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .defaultHeader("appId", "yourAppId") .defaultHeader("timestamp", "yourTimestamp") .defaultHeader("random", "yourRandom") .defaultHeader("msgDigest", "yourMsgDigest") .build(); // 設(shè)置請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 發(fā)送請(qǐng)求 String response = webClient.post() .uri("/target-method") .bodyValue(requestBody) .retrieve() .bodyToMono(String.class) .block(); // 同步調(diào)用 // 輸出響應(yīng)結(jié)果 System.out.println("Response: " + response); } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 支持響應(yīng)式編程,功能強(qiáng)大。
- 缺點(diǎn): API 較復(fù)雜,學(xué)習(xí)曲線較高。
3. 使用 OkHttp
OkHttp
是一個(gè)輕量級(jí)、高性能的 HTTP 客戶端,支持同步和異步調(diào)用。
示例代碼
import okhttp3.*; public class OkHttpExample { public static void main(String[] args) throws Exception { // 創(chuàng)建 OkHttp 客戶端 OkHttpClient client = new OkHttpClient(); // 設(shè)置請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 構(gòu)造請(qǐng)求 Request request = new Request.Builder() .url("https://your-api-url.com/target-method") .post(RequestBody.create(requestBody, MediaType.parse("application/json"))) .addHeader("appId", "yourAppId") .addHeader("timestamp", "yourTimestamp") .addHeader("random", "yourRandom") .addHeader("msgDigest", "yourMsgDigest") .build(); // 發(fā)送請(qǐng)求 try (Response response = client.newCall(request).execute()) { if (response.isSuccessful()) { System.out.println("Response: " + response.body().string()); } else { System.err.println("Request failed: " + response.code()); } } } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 高性能,支持異步調(diào)用。
- 缺點(diǎn): 需要手動(dòng)管理連接,代碼量較多。
4. 使用 Apache HttpClient
Apache HttpClient
是一個(gè)功能強(qiáng)大且穩(wěn)定的 HTTP 客戶端,適合需要復(fù)雜功能(如代理、認(rèn)證、多線程支持)的場(chǎng)景。
示例代碼
import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpClientExample { public static void main(String[] args) throws Exception { // 創(chuàng)建 HttpClient CloseableHttpClient httpClient = HttpClients.createDefault(); // 設(shè)置請(qǐng)求地址 String url = "https://your-api-url.com/target-method"; HttpPost httpPost = new HttpPost(url); // 設(shè)置請(qǐng)求頭 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("appId", "yourAppId"); httpPost.setHeader("timestamp", "yourTimestamp"); httpPost.setHeader("random", "yourRandom"); httpPost.setHeader("msgDigest", "yourMsgDigest"); // 設(shè)置請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; httpPost.setEntity(new StringEntity(requestBody)); // 發(fā)送請(qǐng)求 try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String responseString = EntityUtils.toString(response.getEntity()); System.out.println("Response: " + responseString); } } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 功能強(qiáng)大,支持多線程、代理、連接池等。
- 缺點(diǎn): API 較為復(fù)雜,代碼量較多。
5. 使用 Retrofit
Retrofit
是基于 OkHttp 的類型安全 HTTP 客戶端,適合優(yōu)雅地調(diào)用 REST API。
示例代碼
定義接口
import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Headers; import retrofit2.http.POST; public interface ApiService { @POST("/target-method") @Headers({ "Content-Type: application/json", "appId: yourAppId", "timestamp: yourTimestamp", "random: yourRandom", "msgDigest: yourMsgDigest" }) Call<String> createCz(@Body String requestBody); }
調(diào)用服務(wù)
import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.Call; import retrofit2.Response; public class RetrofitExample { public static void main(String[] args) throws Exception { // 創(chuàng)建 Retrofit 實(shí)例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-url.com") .addConverterFactory(GsonConverterFactory.create()) .build(); // 創(chuàng)建接口實(shí)例 ApiService apiService = retrofit.create(ApiService.class); // 構(gòu)造請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 調(diào)用接口 Call<String> call = apiService.createCz(requestBody); Response<String> response = call.execute(); if (response.isSuccessful()) { System.out.println("Response: " + response.body()); } else { System.err.println("Request failed: " + response.code()); } } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 注解式調(diào)用,簡(jiǎn)潔高效,自動(dòng)處理 JSON。
- 缺點(diǎn): 適合中小型項(xiàng)目,不適合復(fù)雜場(chǎng)景。
6. 使用 HttpURLConnection
HttpURLConnection
是 Java 自帶的原生 HTTP 客戶端,適合不想引入外部依賴的小型項(xiàng)目。
示例代碼
import java.io.OutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpURLConnectionExample { public static void main(String[] args) throws Exception { // 設(shè)置請(qǐng)求地址 URL url = new URL("https://your-api-url.com/target-method"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 設(shè)置請(qǐng)求方法和屬性 connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("appId", "yourAppId"); connection.setRequestProperty("timestamp", "yourTimestamp"); connection.setRequestProperty("random", "yourRandom"); connection.setRequestProperty("msgDigest", "yourMsgDigest"); connection.setDoOutput(true); // 設(shè)置請(qǐng)求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; try (OutputStream os = connection.getOutputStream()) { os.write(requestBody.getBytes()); os.flush(); } // 獲取響應(yīng) int responseCode = connection.getResponseCode(); if (responseCode == 200) { try (BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String inputLine; StringBuilder response = new StringBuilder(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } System.out.println("Response: " + response.toString()); } } else { System.err.println("Request failed: " + responseCode); } } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 無需額外依賴,適合簡(jiǎn)單場(chǎng)景。
- 缺點(diǎn): API 使用繁瑣,功能有限。
7. 使用 OpenFeign
OpenFeign
是 Spring Cloud 提供的聲明式 HTTP 客戶端,適用于微服務(wù)間的接口調(diào)用。
示例代碼
Feign 客戶端接口
import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @FeignClient(name = "czClient", url = "https://your-api-url.com") public interface CzClient { @PostMapping(value = "/target-method") String createCz( @RequestHeader("appId") String appId, @RequestHeader("timestamp") String timestamp, @RequestHeader("random") String random, @RequestHeader("msgDigest") String msgDigest, @RequestBody String requestBody ); }
服務(wù)調(diào)用邏輯
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class CzService { @Autowired private CzClient czClient; public void callCzApi() { String response = czClient.createCz( "yourAppId", "yourTimestamp", "yourRandom", "yourMsgDigest", """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """ ); System.out.println("Response: " + response); } }
優(yōu)缺點(diǎn)
- 優(yōu)點(diǎn): 聲明式調(diào)用,集成 Spring 生態(tài)。
- 缺點(diǎn): 依賴 Spring Cloud,不適用于非 Spring 項(xiàng)目。
總結(jié)
工具 | 適用場(chǎng)景 | 優(yōu)點(diǎn) | 缺點(diǎn) |
---|---|---|---|
RestTemplate | 簡(jiǎn)單的同步調(diào)用 | 簡(jiǎn)單易用 | 已過時(shí),不推薦新項(xiàng)目使用 |
WebClient | 高性能異步調(diào)用、響應(yīng)式場(chǎng)景 | 支持異步與響應(yīng)式調(diào)用 | API 較復(fù)雜 |
OkHttp | 性能要求高的小型項(xiàng)目 | 輕量高效,支持異步調(diào)用 | 需要手動(dòng)管理,代碼量較多 |
Apache HttpClient | 復(fù)雜場(chǎng)景,如代理、多線程、認(rèn)證等 | 功能強(qiáng)大,穩(wěn)定性高 | API 較復(fù)雜 |
Retrofit | 注解式調(diào)用 REST API | 簡(jiǎn)潔高效,自動(dòng)處理 JSON | 適合中小型項(xiàng)目,不適合復(fù)雜場(chǎng)景 |
HttpURLConnection | 極簡(jiǎn)場(chǎng)景,無需額外依賴 | 內(nèi)置支持,無需依賴外部庫 | 使用復(fù)雜,功能有限 |
OpenFeign | 微服務(wù)間的接口調(diào)用 | 聲明式調(diào)用,集成 Spring 生態(tài) | 依賴 Spring Cloud,不適用于非 Spring 項(xiàng)目 |
到此這篇關(guān)于Java 調(diào)用 HTTP 接口的 7 種方式:全網(wǎng)最全指南的文章就介紹到這了,更多相關(guān)Java 調(diào)用 HTTP 接口內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java如何基于okhttp請(qǐng)求SSE接口流式返回詳解
- Java請(qǐng)求Http接口OkHttp超詳細(xì)講解(附帶工具類)
- java+Okhttp3調(diào)用接口的實(shí)例
- Java中的HttpServletRequest接口詳細(xì)解讀
- Java調(diào)用HTTPS接口實(shí)現(xiàn)繞過SSL認(rèn)證
- Java調(diào)用第三方http接口的四種方式總結(jié)
- Java發(fā)送http請(qǐng)求調(diào)用第三方接口獲取token方式
- Java調(diào)用第三方http接口的常用方式總結(jié)
- Java實(shí)現(xiàn)調(diào)用對(duì)方http接口得到返回?cái)?shù)據(jù)
相關(guān)文章
SpringIntegration消息路由之Router的條件路由與過濾功能
本文詳細(xì)介紹了Router的基礎(chǔ)概念、條件路由實(shí)現(xiàn)、基于消息頭的路由、動(dòng)態(tài)路由與路由表、消息過濾與選擇性路由以及錯(cuò)誤處理與路由等方面的內(nèi)容,提高了系統(tǒng)的可維護(hù)性和可擴(kuò)展性,感興趣的朋友一起看看吧2025-04-04Java判斷字符串是否是有效的括號(hào)(實(shí)例詳解)
給定一個(gè)只包括 '(',')','{','}','[',']' 的字符串 s ,判斷字符串是否有效,有效字符串需要滿足:左括號(hào)必須用相同類型的右括號(hào)閉合,這篇文章主要介紹了Java判斷字符串是否是有效的括號(hào),需要的朋友可以參考下2023-10-10Spring@Autowired與@Resource的區(qū)別有哪些
這篇文章主要為大家詳細(xì)介紹了@Autowired與@Resource的區(qū)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-05-05Spring實(shí)現(xiàn)擁有者權(quán)限驗(yàn)證的方法示例
這篇文章主要介紹了Spring實(shí)現(xiàn)擁有者權(quán)限驗(yàn)證的方法示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03Java判斷一個(gè)實(shí)體是不是空的簡(jiǎn)單方法
這篇文章主要給大家介紹了關(guān)于Java判斷一個(gè)實(shí)體是不是空的簡(jiǎn)單方法,實(shí)際項(xiàng)目中我們會(huì)有很多地方需要判空校驗(yàn),文中給出了詳細(xì)的示例代碼,需要的朋友可以參考下2023-07-07java實(shí)現(xiàn)圖片水平和垂直翻轉(zhuǎn)效果
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)圖片水平和垂直翻轉(zhuǎn)效果,圖片旋轉(zhuǎn)的靈活運(yùn)用,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-01-01Java對(duì)象初始化過程代碼塊和構(gòu)造器的調(diào)用順序
這篇文章主要介紹了Java對(duì)象初始化過程代碼塊和構(gòu)造器的調(diào)用順序,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下2022-08-08

springboot整合shardingjdbc實(shí)現(xiàn)分庫分表最簡(jiǎn)單demo