微信開發頻繁涉及 HTTPS 接口調用(獲取 Access Token、上傳素材、發送模板消息等)。本文提供一個生產級 HttpTool,統一處理 SSL 證書信任、連接池、輸出入流、異常與資源釋放,支援 GET、POST、Multipart 文件上傳、媒體素材下載。
TrustManager + HostnameVerifier,適配微信自簽/測試環境證書。finally 塊關閉流與斷開連接,防洩漏。@Component + @Autowired 注入 IoTool 處理流轉換。| 方法 | 用途 | 備註 |
|---|---|---|
sendSSLGetMethod(url) | HTTPS GET 請求 | 返回字串響應 |
sendSSLPostMethod(url, json) | HTTPS POST JSON | 自動設置 Content-Type/Length |
sendSSLMutiPartFormData(url, filePath, formName) | HTTPS 文件上傳 | 構建 multipart/form-data,支援大文件流式寫入 |
sendSSLGetDownloadMedia(url) | HTTPS 下載素材 | 解析 Content-disposition 獲取文件名,返回 Map<fileName, byte[]> |
sendSSLPostDownloadMedia(url, json) | POST 下載素材 | 同上,支援需 POST 參數的下載接口 |
sendGetMethod / sendPostMethod | 普通 HTTP 請求 | 設置 User-Agent、Keep-Alive 等通用頭 |
isAsynchronousRequest(request) | 判斷 AJAX 請求 | 檢測 x-requested-with 或自定義 RequestType 頭 |
// 忽略主機名驗證
private static HostnameVerifier ignoreHostnameVerifier = (s, sslSession) -> true;
// 忽略證書信任鏈
private static TrustManager ignoreCertificationTrustManager = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType) {}
public void checkServerTrusted(X509Certificate[] chain, String authType) {}
public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
};
// 構建 SSLContext
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, new TrustManager[]{ignoreCertificationTrustManager}, new SecureRandom());
connection.setSSLSocketFactory(sslContext.getSocketFactory());
IoTool.getStringFromInputStream / getByteArrayFromInputStream 統一流轉換邏輯。此工具類已在多個微信公眾號/小程序項目中穩定運行,可直接拷貝適配或作為二次封裝基礎。