Java 調用 HTTP 接口的 7 種方式示例代碼(全網(wǎng)最全指南)
Java 調用 HTTP 接口的 7 種方式:全網(wǎng)最全指南
在開發(fā)過程中,調用 HTTP 接口是最常見的需求之一。本文將詳細介紹 Java 中 7 種主流的調用 HTTP 接口的方式,包括每種工具的優(yōu)缺點和完整代碼實現(xiàn)。
1. 使用 RestTemplate
RestTemplate
是 Spring 提供的同步 HTTP 客戶端,適用于傳統(tǒng)項目。盡管從 Spring 5 開始被標記為過時,它仍然是許多開發(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"; // 設置請求頭 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"); // 設置請求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 構造請求 RestTemplate restTemplate = new RestTemplate(); HttpEntity<String> entity = new HttpEntity<>(requestBody, headers); // 發(fā)送請求 ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class); // 輸出響應結果 System.out.println("Response: " + response.getBody()); } }
優(yōu)缺點
- 優(yōu)點: 簡單易用,適合快速開發(fā)。
- 缺點: 已過時,不推薦用于新項目。
2. 使用 WebClient
WebClient
是 Spring 5 引入的現(xiàn)代化 HTTP 客戶端,支持同步和異步調用。
示例代碼
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(); // 設置請求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 發(fā)送請求 String response = webClient.post() .uri("/target-method") .bodyValue(requestBody) .retrieve() .bodyToMono(String.class) .block(); // 同步調用 // 輸出響應結果 System.out.println("Response: " + response); } }
優(yōu)缺點
- 優(yōu)點: 支持響應式編程,功能強大。
- 缺點: API 較復雜,學習曲線較高。
3. 使用 OkHttp
OkHttp
是一個輕量級、高性能的 HTTP 客戶端,支持同步和異步調用。
示例代碼
import okhttp3.*; public class OkHttpExample { public static void main(String[] args) throws Exception { // 創(chuàng)建 OkHttp 客戶端 OkHttpClient client = new OkHttpClient(); // 設置請求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 構造請求 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ā)送請求 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)缺點
- 優(yōu)點: 高性能,支持異步調用。
- 缺點: 需要手動管理連接,代碼量較多。
4. 使用 Apache HttpClient
Apache HttpClient
是一個功能強大且穩(wěn)定的 HTTP 客戶端,適合需要復雜功能(如代理、認證、多線程支持)的場景。
示例代碼
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(); // 設置請求地址 String url = "https://your-api-url.com/target-method"; HttpPost httpPost = new HttpPost(url); // 設置請求頭 httpPost.setHeader("Content-Type", "application/json"); httpPost.setHeader("appId", "yourAppId"); httpPost.setHeader("timestamp", "yourTimestamp"); httpPost.setHeader("random", "yourRandom"); httpPost.setHeader("msgDigest", "yourMsgDigest"); // 設置請求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; httpPost.setEntity(new StringEntity(requestBody)); // 發(fā)送請求 try (CloseableHttpResponse response = httpClient.execute(httpPost)) { String responseString = EntityUtils.toString(response.getEntity()); System.out.println("Response: " + responseString); } } }
優(yōu)缺點
- 優(yōu)點: 功能強大,支持多線程、代理、連接池等。
- 缺點: API 較為復雜,代碼量較多。
5. 使用 Retrofit
Retrofit
是基于 OkHttp 的類型安全 HTTP 客戶端,適合優(yōu)雅地調用 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); }
調用服務
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 實例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-url.com") .addConverterFactory(GsonConverterFactory.create()) .build(); // 創(chuàng)建接口實例 ApiService apiService = retrofit.create(ApiService.class); // 構造請求體 String requestBody = """ { "fileName": "yourFileName", "fileSize": yourFileSize, "dataType": "yourDataType", "certificate": "yourCertificate", "deposit": "yourDeposit", "fileHash": "yourFileHash", "userId": "yourUserId", "appId": "yourAppId" } """; // 調用接口 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)缺點
- 優(yōu)點: 注解式調用,簡潔高效,自動處理 JSON。
- 缺點: 適合中小型項目,不適合復雜場景。
6. 使用 HttpURLConnection
HttpURLConnection
是 Java 自帶的原生 HTTP 客戶端,適合不想引入外部依賴的小型項目。
示例代碼
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 { // 設置請求地址 URL url = new URL("https://your-api-url.com/target-method"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 設置請求方法和屬性 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); // 設置請求體 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(); } // 獲取響應 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)缺點
- 優(yōu)點: 無需額外依賴,適合簡單場景。
- 缺點: API 使用繁瑣,功能有限。
7. 使用 OpenFeign
OpenFeign
是 Spring Cloud 提供的聲明式 HTTP 客戶端,適用于微服務間的接口調用。
示例代碼
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 ); }
服務調用邏輯
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)缺點
- 優(yōu)點: 聲明式調用,集成 Spring 生態(tài)。
- 缺點: 依賴 Spring Cloud,不適用于非 Spring 項目。
總結
工具 | 適用場景 | 優(yōu)點 | 缺點 |
---|---|---|---|
RestTemplate | 簡單的同步調用 | 簡單易用 | 已過時,不推薦新項目使用 |
WebClient | 高性能異步調用、響應式場景 | 支持異步與響應式調用 | API 較復雜 |
OkHttp | 性能要求高的小型項目 | 輕量高效,支持異步調用 | 需要手動管理,代碼量較多 |
Apache HttpClient | 復雜場景,如代理、多線程、認證等 | 功能強大,穩(wěn)定性高 | API 較復雜 |
Retrofit | 注解式調用 REST API | 簡潔高效,自動處理 JSON | 適合中小型項目,不適合復雜場景 |
HttpURLConnection | 極簡場景,無需額外依賴 | 內置支持,無需依賴外部庫 | 使用復雜,功能有限 |
OpenFeign | 微服務間的接口調用 | 聲明式調用,集成 Spring 生態(tài) | 依賴 Spring Cloud,不適用于非 Spring 項目 |
到此這篇關于Java 調用 HTTP 接口的 7 種方式:全網(wǎng)最全指南的文章就介紹到這了,更多相關Java 調用 HTTP 接口內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringIntegration消息路由之Router的條件路由與過濾功能
本文詳細介紹了Router的基礎概念、條件路由實現(xiàn)、基于消息頭的路由、動態(tài)路由與路由表、消息過濾與選擇性路由以及錯誤處理與路由等方面的內容,提高了系統(tǒng)的可維護性和可擴展性,感興趣的朋友一起看看吧2025-04-04Spring@Autowired與@Resource的區(qū)別有哪些
這篇文章主要為大家詳細介紹了@Autowired與@Resource的區(qū)別,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05springboot整合shardingjdbc實現(xiàn)分庫分表最簡單demo
我們知道分庫分表是針對某些數(shù)據(jù)量持續(xù)大幅增長的表,比如用戶表、訂單表等,而不是一刀切將全部表都做分片,這篇文章主要介紹了springboot整合shardingjdbc實現(xiàn)分庫分表最簡單demo,需要的朋友可以參考下2021-06-06