Java爬虫入门(一)使用HttpClient发起Get 或Post请求

掘金原文 传送门

本文参考Java 爬虫学习(一)关于 HttpClient 发起 Get 、Post 请求(想要了解其详细的 可点击此处)

使用HtttpClient模拟客户端爬取网页数据,总的来说,无非就是三个大步骤:

  • 创建HttClient对象(模拟客户端)和设置URI地址
  • 发起请求,获取响应(服务器的反应)
  • 解析消息的内容(头部,实体等)

依据Maven管理的一个项目结构

log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.mr.s = DEBUG

log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c]-[%p] %m%n

pom.xml

<...>
 <dependencies>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>

        </dependency>


        
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.4-alpha1</version>
        </dependency>
       
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpcore</artifactId>
            <version>4.4-alpha1</version>
        </dependency>

    </dependencies>

创建HttpClient对象

创建HttpClient有以下两种方法:

  • 创建基本的HttpClient对象(在每次请求的时候,会存在频繁创建和销毁的问题)
  CloseableHttpClient httpClient = HttpClients.createDefault();
  • 使用连接池创建HttpClient对象
public static void main(String[] args) {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        cm.setMaxTotal(100);

        //设置每个主机的最大连接数
        cm.setDefaultMaxPerRoute(10);

        //使用连接池管理池管理器发起请求
        doGet(cm);
        doGet(cm);
    }

    private static void doGet(PoolingHttpClientConnectionManager cm){
      //设置连接池管理器来创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(),"utf8");
                System.out.println(content.length());


            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {

            //这里不能关掉httpclient  这是由管理池管理的
            if(response != null){
                try {
                    response.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }

    }

创建HttpGet对象完成Get请求

//  方法一 简单地创建
 HttpGet httpGet = new HttpGet("https://www.itcast.cn");
//方法二 带参数的创建

URIBuilder uriBuilder = new URIBuilder("http://yun.itheima.com/search");
uriBuilder.setParameter("key","java");
HttpGet httpGet = new HttpGet(uriBuilder.build());

创建HttpPost完成post请求

//方法一 简单的创建
HttpPost httpPost = new HttpPost("https://www.itcast.cn");

// 方法二  使用表单携带参数来创建
        //创建HttpPost对象
        HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
        //声明List集合  封装表单中的参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        
        params.add(new BasicNameValuePair("key","java"));
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params,"utf8");
        httpPost.setEntity(formEntity);

配置请求信息(可选)

        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) //创建连接的最长时间,单位是毫秒
                .setConnectionRequestTimeout(500)  //设置获取连接的最长时间,单位是毫秒
                .setSocketTimeout(10*1000)  //设置数据传输的最长时间
                .build();
       httpGet.setConfig(config);

一个完整的Demo(使用连接池管理)

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.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

public class HttpClientPoolTest {

    public static void main(String[] args) {
        //创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
        //设置最大连接数
        cm.setMaxTotal(100);

        //设置每个主机的最大连接数
        cm.setDefaultMaxPerRoute(10);

        //使用连接池管理池管理器发起请求
        doGet(cm);
        doGet(cm);
    }

    private static void doGet(PoolingHttpClientConnectionManager cm){
      //设置连接池管理器来创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();

        HttpGet httpGet = new HttpGet("http://www.itcast.cn");
        CloseableHttpResponse response = null;
        try{
            response = httpClient.execute(httpGet);

            if(response.getStatusLine().getStatusCode() == 200){
                String content = EntityUtils.toString(response.getEntity(),"utf8");
                System.out.println(content.length());


            }
        }catch (IOException e){
            e.printStackTrace();
        }finally {

            //这里不能关掉httpclient  这是由管理池管理的
            if(response != null){
                try {
                    response.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
    }

}

如果你喜欢的话,记得点赞,谢谢_

发布了19 篇原创文章 · 获赞 3 · 访问量 3828

猜你喜欢

转载自blog.csdn.net/weixin_42792088/article/details/99840421