TechZhi HTTP Client Starter
- 源碼
- 特性
- 快速開始
- 1. 添加依賴
- 2. 配置
- 3. 使用
- 主要功能
- 支持的HTTP方法
- 文件操作功能
- 高級功能
- 配置示例
- API使用示例
- 基本請求
- 自定義請求
- 異步請求
- 文件操作示例
- 錯誤處理
- 構建和測試
- 依賴說明
本文將介紹一款本人開發的高性能Spring Boot HTTP客戶端Starter,它完美整合了OkHttp和Apache HttpClient。該項目旨在解決原生HTTP客戶端以及RestTemplate在文件上傳下載、異步請求、失敗重試等場景下的復雜性,提供一個配置簡單、功能強大的解決方案。
源碼
https://github.com/ShouZhiDuan/easydo/blob/main/http-client-starter/README.md
特性
- 🚀 高性能: 基于OkHttp和Apache HttpClient 5的高性能HTTP客戶端
- 🔧 易配置: 豐富的配置選項,支持連接池、超時、重試等
- 🔐 安全支持: 支持SSL/TLS配置,可關閉證書校驗
- 🌐 代理支持: 支持HTTP和SOCKS代理配置
- 📝 日志集成: 可配置的請求/響應日志記錄
- 🔄 重試機制: 內置智能重試機制
- 💻 異步支持: 支持同步和異步HTTP請求
- 🎯 類型安全: 自動JSON序列化/反序列化
- 🛠? Spring Boot集成: 無縫集成Spring Boot自動配置
- 📁 文件操作: 完整的文件上傳、下載和流處理支持
- 📊 進度跟蹤: 文件傳輸進度回調和監控
- 🔍 智能檢測: 自動文件類型檢測和Content-Type映射
快速開始
1. 添加依賴
<dependency><groupId>com.techzhi.common</groupId><artifactId>http-client-starter</artifactId><version>1.0.0</version>
</dependency>
2. 配置
techzhi:http-client:enabled: trueclient-type: OK_HTTPconnect-timeout: 10sread-timeout: 30s# 更多配置選項請參考配置文檔
3. 使用
@Service
public class MyService {@Autowiredprivate HttpClient httpClient;@Autowiredprivate HttpClientTemplate httpClientTemplate;public void example() {// 基本GET請求HttpResponse<String> response = httpClient.get("https://api.example.com/data");// 帶類型轉換的GET請求HttpResponse<User> userResponse = httpClient.get("https://api.example.com/user/1", User.class);// POST請求User newUser = new User("John", "john@example.com");HttpResponse<User> createResponse = httpClient.post("https://api.example.com/users", newUser, User.class);// 使用模板類HttpResponse<String> tokenResponse = httpClientTemplate.getWithToken("https://api.example.com/protected", "your-token");}
}
主要功能
支持的HTTP方法
- GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS
- 同步和異步請求
- 自動JSON序列化/反序列化
- 表單提交支持
文件操作功能
- 文件上傳: 支持單個和多個文件上傳
- 多部分表單: multipart/form-data支持,可混合文件和表單字段
- 文件下載: 支持大文件流式下載,自動創建目錄
- 進度回調: 上傳和下載進度實時監控
- 文件流: 獲取文件輸入流和字節數組
- 類型檢測: 自動文件類型檢測和Content-Type映射
- 異步操作: 支持異步文件上傳和下載
高級功能
- 連接池管理
- 代理配置(HTTP/SOCKS)
- SSL/TLS配置(支持關閉證書驗證)
- 重試機制
- 請求/響應日志
- Bearer Token和Basic認證
配置示例
techzhi:http-client:enabled: trueclient-type: OK_HTTP # OK_HTTP 或 APACHE_HTTP_CLIENTconnect-timeout: 10sread-timeout: 30swrite-timeout: 30s# 連接池配置pool:max-total: 200default-max-per-route: 50time-to-live: 5m# 代理配置proxy:enabled: falsetype: HTTPhost: proxy.example.comport: 8080# SSL配置ssl:verify-hostname: trueverify-certificate-chain: true# 重試配置retry:enabled: truemax-attempts: 3retry-interval: 1s
API使用示例
基本請求
// GET請求
HttpResponse<String> response = httpClient.get("https://httpbin.org/get");// POST請求
Map<String, Object> data = Map.of("key", "value");
HttpResponse<String> postResponse = httpClient.post("https://httpbin.org/post", data);
自定義請求
HttpRequest request = HttpRequest.post("https://httpbin.org/post").header("Authorization", "Bearer token").header("Content-Type", "application/json").queryParam("page", "1").jsonBody(requestData);HttpResponse<ResponseData> response = httpClient.execute(request, ResponseData.class);
異步請求
CompletableFuture<HttpResponse<String>> future = httpClient.getAsync("https://httpbin.org/get");
future.thenAccept(response -> {System.out.println("Response: " + response.getBody());
});
文件操作示例
// 1. 單個文件上傳
File file = new File("document.pdf");
HttpResponse<String> uploadResponse = httpClient.uploadFile("https://api.example.com/upload", "file", file
);// 2. 文件上傳帶進度回調
FileProgressCallback progressCallback = new FileProgressCallback() {@Overridepublic void onProgress(long bytesTransferred, long totalBytes, double percentage) {System.out.printf("上傳進度: %.2f%%\n", percentage);}@Overridepublic void onComplete(long totalBytes) {System.out.println("上傳完成: " + totalBytes + " bytes");}
};httpClient.uploadFile("https://api.example.com/upload", "file", file, progressCallback);// 3. 多文件上傳
List<MultipartFile> files = Arrays.asList(MultipartFile.of("file1", new File("doc1.pdf")),MultipartFile.of("file2", new File("doc2.pdf")),MultipartFile.of("data", "info.json", jsonData.getBytes(), "application/json")
);HttpResponse<String> multiResponse = httpClient.uploadFiles("https://api.example.com/upload", files);// 4. 文件和表單數據混合上傳
Map<String, String> formFields = new HashMap<>();
formFields.put("title", "文檔標題");
formFields.put("category", "技術文檔");httpClient.uploadFilesWithForm("https://api.example.com/upload", files, formFields);// 5. 文件下載
boolean downloadSuccess = httpClient.downloadFile("https://api.example.com/download/report.pdf", "/path/to/save/report.pdf"
);// 6. 文件下載帶進度回調
httpClient.downloadFile("https://api.example.com/download/large-file.zip", "/path/to/save/large-file.zip", progressCallback
);// 7. 獲取文件字節數組
byte[] fileBytes = httpClient.getFileBytes("https://api.example.com/download/small-file.txt");// 8. 獲取文件流
try (InputStream fileStream = httpClient.getFileStream("https://api.example.com/download/data.csv")) {// 處理文件流BufferedReader reader = new BufferedReader(new InputStreamReader(fileStream));String line;while ((line = reader.readLine()) != null) {// 處理每一行}
}// 9. 異步文件操作
CompletableFuture<HttpResponse<String>> asyncUpload = httpClient.uploadFileAsync("https://api.example.com/upload", "file", file
);CompletableFuture<Boolean> asyncDownload = httpClient.downloadFileAsync("https://api.example.com/download/file.zip", "/path/to/save/file.zip"
);
錯誤處理
HttpResponse<String> response = httpClient.get("https://httpbin.org/status/404");if (response.isSuccessful()) {String data = response.getBody();
} else if (response.isClientError()) {System.out.println("Client error: " + response.getStatusCode());
} else if (response.isServerError()) {System.out.println("Server error: " + response.getStatusCode());
}
構建和測試
# 編譯項目
mvn clean compile# 運行測試
mvn test# 打包
mvn clean package# 安裝到本地倉庫
mvn install
依賴說明
本項目支持以下HTTP客戶端實現:
- OkHttp: 默認實現,高性能、輕量級
- Apache HttpClient 5: 功能豐富,企業級特性
根據項目需求選擇合適的實現,通過配置techzhi.http-client.client-type
來切換。