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)缺點和完整代碼實現(xiàn)。
1. 使用 RestTemplate
RestTemplate 是 Spring 提供的同步 HTTP 客戶端,適用于傳統(tǒng)項目。盡管從 Spring 5 開始被標(biāo)記為過時,它仍然是許多開發(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è)置請求頭
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è)置請求體
String requestBody = """
{
"fileName": "yourFileName",
"fileSize": yourFileSize,
"dataType": "yourDataType",
"certificate": "yourCertificate",
"deposit": "yourDeposit",
"fileHash": "yourFileHash",
"userId": "yourUserId",
"appId": "yourAppId"
}
""";
// 構(gòu)造請求
RestTemplate restTemplate = new RestTemplate();
HttpEntity<String> entity = new HttpEntity<>(requestBody, headers);
// 發(fā)送請求
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
// 輸出響應(yīng)結(jié)果
System.out.println("Response: " + response.getBody());
}
}優(yōu)缺點
- 優(yōu)點: 簡單易用,適合快速開發(fā)。
- 缺點: 已過時,不推薦用于新項目。
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è)置請求體
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(); // 同步調(diào)用
// 輸出響應(yīng)結(jié)果
System.out.println("Response: " + response);
}
}優(yōu)缺點
- 優(yōu)點: 支持響應(yīng)式編程,功能強大。
- 缺點: API 較復(fù)雜,學(xué)習(xí)曲線較高。
3. 使用 OkHttp
OkHttp 是一個輕量級、高性能的 HTTP 客戶端,支持同步和異步調(diào)用。
示例代碼
import okhttp3.*;
public class OkHttpExample {
public static void main(String[] args) throws Exception {
// 創(chuàng)建 OkHttp 客戶端
OkHttpClient client = new OkHttpClient();
// 設(shè)置請求體
String requestBody = """
{
"fileName": "yourFileName",
"fileSize": yourFileSize,
"dataType": "yourDataType",
"certificate": "yourCertificate",
"deposit": "yourDeposit",
"fileHash": "yourFileHash",
"userId": "yourUserId",
"appId": "yourAppId"
}
""";
// 構(gòu)造請求
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)點: 高性能,支持異步調(diào)用。
- 缺點: 需要手動管理連接,代碼量較多。
4. 使用 Apache HttpClient
Apache HttpClient 是一個功能強大且穩(wěn)定的 HTTP 客戶端,適合需要復(fù)雜功能(如代理、認(rèn)證、多線程支持)的場景。
示例代碼
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è)置請求地址
String url = "https://your-api-url.com/target-method";
HttpPost httpPost = new HttpPost(url);
// 設(shè)置請求頭
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("appId", "yourAppId");
httpPost.setHeader("timestamp", "yourTimestamp");
httpPost.setHeader("random", "yourRandom");
httpPost.setHeader("msgDigest", "yourMsgDigest");
// 設(shè)置請求體
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 較為復(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 實例
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://your-api-url.com")
.addConverterFactory(GsonConverterFactory.create())
.build();
// 創(chuàng)建接口實例
ApiService apiService = retrofit.create(ApiService.class);
// 構(gòu)造請求體
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)缺點
- 優(yōu)點: 注解式調(diào)用,簡潔高效,自動處理 JSON。
- 缺點: 適合中小型項目,不適合復(fù)雜場景。
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 {
// 設(shè)置請求地址
URL url = new URL("https://your-api-url.com/target-method");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
// 設(shè)置請求方法和屬性
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è)置請求體
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)缺點
- 優(yōu)點: 無需額外依賴,適合簡單場景。
- 缺點: 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)缺點
- 優(yōu)點: 聲明式調(diào)用,集成 Spring 生態(tài)。
- 缺點: 依賴 Spring Cloud,不適用于非 Spring 項目。
總結(jié)
| 工具 | 適用場景 | 優(yōu)點 | 缺點 |
|---|---|---|---|
| RestTemplate | 簡單的同步調(diào)用 | 簡單易用 | 已過時,不推薦新項目使用 |
| WebClient | 高性能異步調(diào)用、響應(yīng)式場景 | 支持異步與響應(yīng)式調(diào)用 | API 較復(fù)雜 |
| OkHttp | 性能要求高的小型項目 | 輕量高效,支持異步調(diào)用 | 需要手動管理,代碼量較多 |
| Apache HttpClient | 復(fù)雜場景,如代理、多線程、認(rèn)證等 | 功能強大,穩(wěn)定性高 | API 較復(fù)雜 |
| Retrofit | 注解式調(diào)用 REST API | 簡潔高效,自動處理 JSON | 適合中小型項目,不適合復(fù)雜場景 |
| HttpURLConnection | 極簡場景,無需額外依賴 | 內(nèi)置支持,無需依賴外部庫 | 使用復(fù)雜,功能有限 |
| OpenFeign | 微服務(wù)間的接口調(diào)用 | 聲明式調(diào)用,集成 Spring 生態(tài) | 依賴 Spring Cloud,不適用于非 Spring 項目 |
到此這篇關(guān)于Java 調(diào)用 HTTP 接口的 7 種方式:全網(wǎng)最全指南的文章就介紹到這了,更多相關(guān)Java 調(diào)用 HTTP 接口內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Java如何基于okhttp請求SSE接口流式返回詳解
- Java請求Http接口OkHttp超詳細(xì)講解(附帶工具類)
- java+Okhttp3調(diào)用接口的實例
- Java中的HttpServletRequest接口詳細(xì)解讀
- Java調(diào)用HTTPS接口實現(xiàn)繞過SSL認(rèn)證
- Java調(diào)用第三方http接口的四種方式總結(jié)
- Java發(fā)送http請求調(diào)用第三方接口獲取token方式
- Java調(diào)用第三方http接口的常用方式總結(jié)
- Java實現(xiàn)調(diào)用對方http接口得到返回數(shù)據(jù)
相關(guān)文章
SpringIntegration消息路由之Router的條件路由與過濾功能
本文詳細(xì)介紹了Router的基礎(chǔ)概念、條件路由實現(xiàn)、基于消息頭的路由、動態(tài)路由與路由表、消息過濾與選擇性路由以及錯誤處理與路由等方面的內(nèi)容,提高了系統(tǒng)的可維護(hù)性和可擴展性,感興趣的朋友一起看看吧2025-04-04
Spring@Autowired與@Resource的區(qū)別有哪些
這篇文章主要為大家詳細(xì)介紹了@Autowired與@Resource的區(qū)別,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02
Spring @Value如何通過${}、#{}注入不同類型的值
這篇文章主要介紹了Spring @Value如何通過${}、#{}注入不同類型的值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-05-05
Spring實現(xiàn)擁有者權(quán)限驗證的方法示例
這篇文章主要介紹了Spring實現(xiàn)擁有者權(quán)限驗證的方法示例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-03-03
java實現(xiàn)圖片水平和垂直翻轉(zhuǎn)效果
這篇文章主要為大家詳細(xì)介紹了java實現(xiàn)圖片水平和垂直翻轉(zhuǎn)效果,圖片旋轉(zhuǎn)的靈活運用,具有一定的參考價值,感興趣的小伙伴們可以參考一下2019-01-01
Java對象初始化過程代碼塊和構(gòu)造器的調(diào)用順序
這篇文章主要介紹了Java對象初始化過程代碼塊和構(gòu)造器的調(diào)用順序,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-08-08
springboot整合shardingjdbc實現(xiàn)分庫分表最簡單demo

