HTTP 客戶端使用指南
Package:
io.leandev.appfuse.http.*狀態: 穩定(Phase 1-2 已完成)
簡介
HTTP 客戶端模組提供基於 Apache HttpClient 5.x 的 HTTP 請求功能,支援重試機制、Gateway 轉發和 OAuth2 認證。
核心特色
| 特色 | 說明 |
|---|---|
| Builder 模式 | 流暢的客戶端配置 |
| 自動序列化 | JSON/XML 序列化與反序列化 |
| 重試機制 | 自動重試失敗請求 |
| Gateway 轉發 | 支援 API Gateway |
| OAuth2 整合 | 自動附加認證令牌 |
| 攔截器 | 日誌、監控擴充 |
快速開始
基本 GET 請求
import io.leandev.appfuse.http.*;
StandardHttpClient httpClient = new StandardHttpClient();
try {
HttpGet request = new HttpGet("https://api.example.com/users/123");
ClassicHttpResponse response = httpClient.execute(request);
HttpResponseParser parser = new HttpResponseParser();
User user = parser.read(response, User.class);
System.out.println("User: " + user.getName());
} finally {
httpClient.close();
}
POST 請求 with JSON Body
StandardHttpClient httpClient = new StandardHttpClient();
try {
User newUser = new User("john", "john@example.com");
String json = new ObjectMapper().writeValueAsString(newUser);
HttpPost request = new HttpPost("https://api.example.com/users");
request.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
ClassicHttpResponse response = httpClient.execute(request);
System.out.println("Status: " + response.getCode());
} finally {
httpClient.close();
}
使用 Builder 配置
StandardHttpClient httpClient = StandardHttpClient.builder()
.withTimeout(30) // 30 秒 timeout
.withMaxTotal(200) // 最大連線數 200
.withDefaultMaxPerRoute(100) // 每個路由最大連線數
.withAuthenticator(() -> getAccessToken()) // OAuth2 認證
.withLogging() // 啟用日誌
.build();
try {
HttpGet request = new HttpGet("https://api.example.com/protected");
ClassicHttpResponse response = httpClient.execute(request);
// ... 處理回應
} finally {
httpClient.close();
}
常見場景
場景 1: 帶重試的請求
StandardHttpClient httpClient = new StandardHttpClient();
httpClient.setRetries(3); // 失敗時重試 3 次
HttpGet request = new HttpGet("https://api.example.com/unstable");
ClassicHttpResponse response = httpClient.execute(request);
場景 2: Gateway 轉發
URL gateway = new URL("https://gateway.example.com");
StandardHttpClient httpClient = StandardHttpClient.builder()
.usingGateway(gateway)
.build();
// 實際請求會被轉發到 gateway
HttpGet request = new HttpGet("https://api.example.com/users");
ClassicHttpResponse response = httpClient.execute(request);
場景 3: 自訂攔截器
HttpClientInterceptor customInterceptor = new HttpClientInterceptor() {
@Override
public void beforeRequest(InterceptorContext context, ClassicHttpRequest request) {
request.addHeader("X-Custom-Header", "value");
}
@Override
public void afterResponse(InterceptorContext context,
ClassicHttpRequest request,
ClassicHttpResponse response) {
System.out.println("Status: " + response.getCode());
}
@Override
public void onError(InterceptorContext context,
ClassicHttpRequest request,
Exception error) {
System.err.println("Error: " + error.getMessage());
}
};
StandardHttpClient httpClient = StandardHttpClient.builder()
.withInterceptor(customInterceptor)
.build();
場景 4: 查詢連線池狀態
StandardHttpClient httpClient = StandardHttpClient.builder()
.withMaxTotal(100)
.build();
StandardHttpClient.Stats stats = httpClient.getTotalStats();
System.out.println("Leased: " + stats.getLeased());
System.out.println("Available: " + stats.getAvailable());
System.out.println("Pending: " + stats.getPending());
核心組件
StandardHttpClient
HTTP 客戶端核心類別:
- HTTP 請求執行
- 重試機制
- 認證處理
- Gateway 轉發
- 攔截器支援
- 連線池管理
HttpResponseParser / HttpRequestParser
序列化與反序列化工具:
- JSON 轉 Java 物件
- XML 轉 Java 物件
- 支援泛型集合
NameValuePairs
參數轉換工具:
User user = new User("john", 25);
List<NameValuePair> params = NameValuePairs.of(user);
// 產生: [username=john, age=25]
進階配置
停用 SSL 驗證(僅限開發環境)
StandardHttpClient httpClient = StandardHttpClient.builder()
.disableSSLVerification() // ⚠️ 不可用於生產環境
.build();
⚠️ 警告: 在生產環境停用 SSL 驗證會有嚴重安全風險!
處理大型回應
// 不要使用 parser,直接處理 stream
HttpEntity entity = response.getEntity();
try (InputStream is = entity.getContent()) {
// 串流處理
}
與其他工具的比較
| 特性 | AppFuse HTTP | RestTemplate | WebClient |
|---|---|---|---|
| 基礎框架 | Apache HttpClient 5.x | Apache HttpClient | Reactor Netty |
| 程式模型 | 同步 | 同步 | 非同步/響應式 |
| 重試機制 | ✅ 內建 | ❌ 需自行實作 | ✅ 內建 |
| Gateway 轉發 | ✅ 內建 | ❌ | ❌ |
選擇建議:
- 一般 Spring 應用 → RestTemplate 或 WebClient
- 需要重試/Gateway 轉發 → AppFuse HTTP
- 非 Spring 應用 → AppFuse HTTP
- 響應式應用 → WebClient
常見問題
Q: 為什麼不直接用 RestTemplate?
A: AppFuse HTTP 針對特定需求設計:內建重試機制、Gateway 轉發、不依賴 Spring。如果您的應用已使用 Spring,RestTemplate 是更好的選擇。
Q: 支援響應式程式設計嗎?
A: 目前不支援。本模組基於同步阻塞模型。如需響應式,請使用 WebClient。
API 參考
詳細的類別設計和方法簽名,請參閱 API 參考: HTTP 或 Javadoc。