Apache HttpClient是一個開源的Java庫,用于發送HTTP請求并與HTTP服務器進行通信。它提供了一組易于使用的API,可以進行各種HTTP操作,如發送GET、POST、PUT、DELETE請求,設置請求頭、請求參數、響應處理等。
以下是Apache HttpClient的基本使用步驟:
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://www.example.com");
httpGet.addHeader("Authorization", "Bearer token123");
httpPost.setEntity(new StringEntity("param1=value1¶m2=value2"));
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
Header[] headers = httpResponse.getAllHeaders();
String responseBody = EntityUtils.toString(httpResponse.getEntity());
httpClient.close();
httpResponse.close();
需要注意的是,Apache HttpClient提供了很多高級功能和配置選項,如連接池管理、代理設置、重試機制等,可以根據實際需求進行配置和使用。