Apache HttpClient是一個功能強大且靈活的Java HTTP客戶端庫,廣泛用于Java應用程序中的網絡通信。它提供了豐富的API來執行HTTP請求和處理HTTP響應,支持從簡單的GET和POST請求到復雜的HTTP/2和WebSocket通信。以下是Apache HttpClient的一些關鍵特性和使用示例:
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
public class HttpClientDemo {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpGet httpGet = new HttpGet("https://api.example.com/users");
try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println("響應狀態:" + response.getStatusLine());
System.out.println("響應內容:" + result);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.HttpPost;
public class HttpClientPostDemo {
public static void main(String[] args) {
try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
HttpPost httpPost = new HttpPost("https://api.example.com/users");
httpPost.setHeader("Content-Type", "application/json");
String jsonBody = "{\"name\":\"小魚\",\"age\":25}";
StringEntity entity = new StringEntity(jsonBody, "UTF-8");
httpPost.setEntity(entity);
try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
System.out.println(response.getStatusLine());
String responseBody = EntityUtils.toString(response.getEntity());
System.out.println(responseBody);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setMaxTotal(200); // 最大連接數
cm.setDefaultMaxPerRoute(20); // 每個路由默認最大連接數
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
// 使用 httpClient 發送請求...
在使用Apache HttpClient時,建議查看最新的官方文檔以獲取最準確的信息和示例代碼。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。