HttpClient爬取网页

最近学习了HttpClient,做一些必要的笔记,一来是对自己学习的知识的巩固,二来对有同样问题的人有参考作用



一 HttpClient简介

   HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

二 HttpClient特性

  1. 实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
  2. 支持自动转向
  3. 支持 HTTPS 协议
  4. 支持代理服务器等

三 开发思路

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可:

  1. 创建HttpClient对象。
  2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
  3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
  4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
  5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
  6. 释放连接。无论执行方法是否成功,都必须释放连接

四 高匿ip爬取网页举例

  1. 需要的包
<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

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

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.5</version>
    </dependency>
</dependencies>
  1. 完整代码
public class Demo6 {

    public static void main(String[] args) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault(); //创建httpClient实例
        HttpGet httpGet = new HttpGet("http://www.java1234.com/"); //创建httpGet实例
        HttpHost proxy = new HttpHost("221.180.170.104",8080); 
        RequestConfig config = RequestConfig.custom()
                .setProxy(proxy) ////设置高匿ip
                .setConnectTimeout(10000) //设置连接超时时间 10秒钟
                .setSocketTimeout(10000) //设置读取超时时间  10秒钟
                .build();
        httpGet.setConfig(config);
        httpGet.setHeader("User-Agent","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36"); //模拟谷歌浏览器
        CloseableHttpResponse response = httpClient.execute(httpGet); //发送http get请求
        HttpEntity entity = response.getEntity(); //获取返回实体
        System.out.println("网页内容:"+ EntityUtils.toString(entity,"utf-8")); //获取网页内容
        response.close(); //response关闭
        httpClient.close(); //httpclient关闭
    }
    
}

五 总结

   如有错误恳请指正,如有侵权请联系我删除
   参考文章: HttpClient用法–这一篇全了解

猜你喜欢

转载自blog.csdn.net/qq_39007083/article/details/106307529