中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

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
惠水县| 绥滨县| 宣城市| 宁远县| 揭东县| 武城县| 虎林市| 财经| 雅江县| 罗山县| 龙井市| 乌海市| 仪陇县| 新绛县| 连城县| 中江县| 礼泉县| 昌平区| 新河县| 盐城市| 安吉县| 易门县| 荥经县| 剑川县| 金塔县| 潼关县| 泸水县| 兴宁市| 黄冈市| 德惠市| 油尖旺区| 赤峰市| 屏东市| 潼南县| 泗水县| 孝义市| 沾益县| 突泉县| 太白县| 固阳县| 社旗县|