瀏覽器獲取資料: 打開瀏覽器 ==> 輸入網址 ==> 回車查詢 ==> 回傳結果 ==> 瀏覽器顯示結果資料
HttpClient獲取資料: 創建HttpClient ==> 創建請求方式 ==> 發送請求 ==> 回應結果 ==> 決議結果資料
0. 操作摘要
0.1 添加依賴
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
0.2 代碼
//1. 打開瀏覽器 創建httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); //2. 輸入網址 HttpGet httpGet = new HttpGet("http://www.baidu.com"); //3. 發送請求 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //4. 回應結果 HttpEntity httpEntity = httpResponse.getEntity(); //5. 決議結果 String result = EntityUtils.toString(httpEntity, "utf-8"); System.out.println(result);
1. 實操
1.1 添加依賴
1.1.1 找到 pom.xml 添加依賴

1.1.2 依賴代碼
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
1.2 添加 TestHttpClient 類
1.2.1 創建類檔案 com.aifu.TestHttpClient

1.2.2 添加代碼

public static void main(String[] args) throws IOException { //1. 打開瀏覽器 創建httpclient物件 CloseableHttpClient httpClient = HttpClients.createDefault(); //2. 輸入網址 HttpGet httpGet = new HttpGet("http://www.baidu.com"); //3. 發送請求 CloseableHttpResponse httpResponse = httpClient.execute(httpGet); //4. 回應結果 HttpEntity httpEntity = httpResponse.getEntity(); //5. 決議結果 String result = EntityUtils.toString(httpEntity, "utf-8"); System.out.println(result); }
1.3 運行
1.3.1 點擊綠標運行 或者快捷鍵 ctrl + alt +F10

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/134857.html
標籤:Java
上一篇:20200725_java爬蟲_專案創建及log4j配置
下一篇:PHP 類/物件函式
