功能豐富:連線池、自動重試、攔截器、多執行緒安全、支援各種認證機制。
public static String sendUrlRequest(String urlStr, String param1, String param2) throws Exception {
HttpClient httpClient = new DefaultHttpClient();
// 連線池與超時配置
httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 20000);
httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 20000);
List<NameValuePair> nvps = new ArrayList<>();
nvps.add(new BasicNameValuePair("mainMemoCode", param1));
nvps.add(new BasicNameValuePair("recordPassWord", param2));
HttpPost httpPost = new HttpPost(urlStr);
httpPost.setEntity(new UrlEncodedFormEntity(nvps, "GBK")); // 編碼視伺服器而定
HttpResponse response = httpClient.execute(httpPost);
String contentType = response.getHeaders("Content-Type")[0].getValue();
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
httpPost.abort();
httpClient.getConnectionManager().shutdown();
return result;
}
PoolingClientConnectionManager 可複用連線,高併發效能優異HttpEntity 支援大檔案不佔記憶體public static String sendUrlRequest(String urlStr, String param) throws Exception {
HttpURLConnection conn = null;
try {
URL url = new URL(urlStr);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("User-Agent", "directclient");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=GBK");
try (PrintWriter out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "GBK"))) {
out.println(param);
}
StringBuilder sb = new StringBuilder();
try (BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "GBK"))) {
String line;
while ((line = in.readLine()) != null) sb.append(line);
}
return sb.toString();
} finally {
if (conn != null) conn.disconnect();
}
}
| 維度 | HttpClient 4.x | HttpURLConnection |
|---|---|---|
| 依賴 | ~500KB JAR | 零依賴 |
| 連線池 | 內建 | 無 |
| API 複雜度 | 中等 | 較繁瑣 |
| HTTPS 自簽憑證 | 易配置 | 需自定 TrustManager |
| 多執行緒安全 | 是 | 每請求新建連線 |
| 維護狀態 | 活躍(5.x 版本) | JDK 內建持續更新 |
java.net.http.HttpClient (API 29+)HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(urlStr))
.header("Content-Type", "application/x-www-form-urlencoded")
.POST(HttpRequest.BodyPublishers.ofString(params))
.build();
String response = client.send(request, HttpResponse.BodyHandlers.ofString()).body();
標準化、支援 HTTP/2、非阻塞、函數式 API,長期來看為最佳選擇。