Java网络爬虫(一)HttpClient使用

本系列使用HttpClient+Jsoup实现网络爬虫。
在Maven pom.xml中天假httpclient依赖

  <dependency>
      <groupId>org.apache.httpcomponents</groupId>
      <artifactId>httpclient</artifactId>
      <version>4.5.2</version>
 </dependency>

以下Java代码,可以实现将网易首页HTML代码打印在控制台上。

 public static void main(String[] args) throws IOException {
    
    
        //通过HttpClients工具类创建一个httpClient对象,该用来发起HTTP请求
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建一个“HTTP请求方法为Get”的一个对象
        HttpGet httpGet = new HttpGet("http://www.sina.com.cn/");
        //通过httpClient发其Http请求,得到Http响应
        CloseableHttpResponse response = httpClient.execute(httpGet);
        //处理响应
        //如果响应状态码是200,表示访问的网页是正常的
        if (response.getStatusLine().getStatusCode() == 200) {
    
    
            //拿到响应内容
            HttpEntity entity = response.getEntity();
            //将内容转换成String
            String content = EntityUtils.toString(entity, "UTF-8");
            //将内容打印在控制台上
            System.out.println(content);
        }
    }

おすすめ

転載: blog.csdn.net/GodBlessYouAndMe/article/details/120560961