Apache HttpClient 是 Apache Jakarta Commons 子項目,提供高效、功能豐富的 HTTP 協議客戶端編程支持。相比 JDK 原生 URLConnection,它在易用性、靈活性、連接管理、認證機制等方面優勢明顯,廣泛應用於 Cactus、HTMLUnit 等知名開源項目。
CloseableHttpClient 實例HttpGet/HttpPost 等)並設置 URLsetEntity/setParams)execute() 發送請求獲取 CloseableHttpResponseHttpEntity)finally 塊中關閉)public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
HttpGet httpget = new HttpGet("https://www.baidu.com/");
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println(EntityUtils.toString(entity));
}
} finally { response.close(); }
} catch (Exception e) { e.printStackTrace(); }
finally { try { httpclient.close(); } catch (IOException e) { e.printStackTrace(); } }
}
public void postForm() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://localhost:8080/login");
List formparams = new ArrayList<>();
formparams.add(new BasicNameValuePair("username", "admin"));
formparams.add(new BasicNameValuePair("password", "123456"));
httppost.setEntity(new UrlEncodedFormEntity(formparams, "UTF-8"));
// execute 並處理響應...
}
public void ssl() {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(new FileInputStream("d:\\tomcat.keystore"), "123456".toCharArray());
SSLContext sslcontext = SSLContexts.custom()
.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy()).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext,
new String[]{"TLSv1"}, null, SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
// 執行 HTTPS 請求...
}
public void upload() {
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost("https://localhost:8080/upload");
FileBody bin = new FileBody(new File("F:\\image\\sendpix0.jpg"));
StringBody comment = new StringBody("備註", ContentType.TEXT_PLAIN);
HttpEntity reqEntity = MultipartEntityBuilder.create()
.addPart("bin", bin).addPart("comment", comment).build();
httppost.setEntity(reqEntity);
// execute 並處理響應...
}
PoolingHttpClientConnectionManager)提升多線程性能HttpClient 實例