亚洲激情专区-91九色丨porny丨老师-久久久久久久女国产乱让韩-国产精品午夜小视频观看

溫馨提示×

HttpClient基本功能的使用Get方式

小云
98
2023-09-23 08:00:52
欄目: 編程語言

HttpClient是一個開源的Java HTTP客戶端庫,可以發送HTTP請求,并接收HTTP響應。

使用HttpClient發送GET請求的基本步驟如下:

  1. 創建HttpClient對象:
CloseableHttpClient httpClient = HttpClients.createDefault();
  1. 創建HttpGet對象,并設置請求的URL:
HttpGet httpGet = new HttpGet("http://www.example.com");
  1. 執行GET請求并獲取響應:
CloseableHttpResponse response = httpClient.execute(httpGet);
  1. 解析響應:
  • 獲取響應狀態碼:
int statusCode = response.getStatusLine().getStatusCode();
  • 獲取響應內容:
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
  1. 關閉HttpClient和HttpResponse:
response.close();
httpClient.close();

完整的示例代碼如下:

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) throws Exception {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpGet httpGet = new HttpGet("http://www.example.com");
CloseableHttpResponse response = httpClient.execute(httpGet);
try {
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
String responseContent = EntityUtils.toString(entity, "UTF-8");
System.out.println("Status Code: " + statusCode);
System.out.println("Response Content: " + responseContent);
} finally {
response.close();
}
httpClient.close();
}
}

以上代碼發送一個GET請求到http://www.example.com,并輸出響應狀態碼和響應內容。

0
万州区| 兴和县| 武穴市| 黄平县| 鲁山县| 辽阳县| 荆门市| 金坛市| 施甸县| 靖边县| 梅河口市| 怀柔区| 成武县| 新民市| 德昌县| 皮山县| 积石山| 连平县| 荔波县| 新竹县| 永昌县| 临湘市| 商水县| 阳西县| 安乡县| 南京市| 黑河市| 城市| 楚雄市| 莱阳市| 登封市| 永和县| 永仁县| 梨树县| 阆中市| 开化县| 米脂县| 金溪县| 延安市| 大余县| 阜康市|