HttpClient 是一個開源的Java HTTP客戶端庫,用于發送HTTP請求和處理響應。
以下是使用HttpClient的基本步驟:
導入HttpClient庫。
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
創建HttpClient實例。
HttpClient httpClient = HttpClientBuilder.create().build();
創建HTTP請求對象,如HttpGet或HttpPost。
HttpGet httpGet = new HttpGet("http://www.example.com");
HttpPost httpPost = new HttpPost("http://www.example.com");
發送HTTP請求并獲取響應。
CloseableHttpResponse response = httpClient.execute(httpGet);
處理響應。
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity());
關閉響應和HttpClient。
response.close();
httpClient.close();
以上是基本的使用方法,你可以根據需求進行更多的操作,如添加請求頭、設置請求參數等。