91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

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
堆龙德庆县| 无极县| 福泉市| 两当县| 涞源县| 桐庐县| 阿鲁科尔沁旗| 焦作市| 达州市| 松江区| 辰溪县| 开封市| 秀山| 进贤县| 泸州市| 隆林| 德兴市| 通渭县| 二手房| 白山市| 横峰县| 常德市| 高州市| 蕉岭县| 宁德市| 阳西县| 保靖县| 嫩江县| 新河县| 北宁市| 永济市| 靖边县| 三河市| 阿勒泰市| 昌邑市| 务川| 枣阳市| 远安县| 佛教| 长沙县| 伊宁市|