Java爬虫之HttpClient的使用

HttpClient

导入httpclient依赖

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

Get请求

public class HttpGetTest {
    public static void main(String[] args) {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet对象,设置url访问地址
        HttpGet httpGet = new HttpGet("https://www.baidu.com");
        CloseableHttpResponse response = null;
        try {
        	//解析响应
            //使用httpGet发起请求,获取response对象
             response = httpClient.execute(httpGet);
             //获取请求的状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        //释放资源
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

请求成功,返回数据进行打印

在这里插入图片描述
现在问题来了,如果想要获取下面的数据怎么办,就是带有参数的请求
在这里插入图片描述

带parms的Get请求

点击进去看HttpGet会发现HttpGet有几种构造方式,第一种就是我们上面提到的直接一个地址www.baidu.com,其实我们要携带参数直接访问http://search.dangdang.com/?key=Java&act=input即可,就可以直接获取当页的数据,但是我们不可能一需要查什么就查询什么链接吧,我们需要的是参数可以随时变化,所以使用我们的第二种方式传URI

在这里插入图片描述

package com.lin.httpclient;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author LCW
 * @since 2020/6/21 14:56
 */
public class httpGetPramsTest {
    public static void main(String[] args) throws Exception {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("http://search.dangdang.com");
        //这里有多少个参数就.addParameter多少个
        uriBuilder.addParameter("key", "Java")
                  .addParameter("act", "input");

        //创建httpGet对象,设置url访问地址
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        System.out.println("发起请求的信息:" + httpGet);
        CloseableHttpResponse response = null;
        try {
            //使用httpGet发起请求,获取response对象
             response = httpClient.execute(httpGet);
             //获取请求的状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}


在这里插入图片描述

讲完Get请求,接下来说一下Post请求

package com.lin.httpclient;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * @author LCW
 * @since 2020/6/21 14:56
 */
public class HttpPostTest {
    public static void main(String[] args) {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet对象,设置url访问地址
        HttpPost httpPost = new HttpPost("http://www.dangdang.com");
        CloseableHttpResponse response = null;
        try {
            //使用httpGet发起请求,获取response对象
             response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

在这里插入图片描述

Post的带参数的请求,还是访问当当搜索Java

package com.lin.httpclient;

import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author LCW
 * @since 2020/6/21 14:56
 */
public class HttpPostPramsTest {
    public static void main(String[] args) throws UnsupportedEncodingException {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet对象,设置url访问地址
        HttpPost httpPost = new HttpPost("http://search.dangdang.com");
        //声明list集合,封装表单张的参数
        List<NameValuePair> parms = new ArrayList<>();
        //创建表单的entity对象
        parms.add(new BasicNameValuePair("key", "java"));
        parms.add(new BasicNameValuePair("act", "input"));

        //创建表单的Entity对象
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parms, "utf8");

        //设置表单的Entity对象到post请求中
        httpPost.setEntity(formEntity);

        CloseableHttpResponse response = null;
        try {
            //使用httpGet发起请求,获取response对象
             response = httpClient.execute(httpPost);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

在这里插入图片描述

创建连接池

package com.lin.httpclient;

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(200);

        //设置每个主机的最大连接数  访问一个网站的最大连接属
        cm.setDefaultMaxPerRoute(10);

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

    }

    private static void doGet(PoolingHttpClientConnectionManager cm) {
        //通过PoolingHttpClientConnectionManager创建创建httpClient
        CloseableHttpClient httpClient =
                HttpClients.custom().setConnectionManager(cm).build();
        //接下来的跟get请求一样
        HttpGet httpGet = new HttpGet("http://search.dangdang.com");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();

        } finally {
            //注意这里不用释放httpget,现在将给连接池进行统一管理
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}

httpClient的一些配置

package com.lin.httpclient;

import org.apache.http.client.config.RequestConfig;
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;

import java.io.IOException;

/**
 * @author LCW
 * @since 2020/6/21 14:56
 */
public class HttpConfigTest {
    public static void main(String[] args) {
        //创建httpclient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        //创建httpGet对象,设置url访问地址
        HttpGet httpGet = new HttpGet("https://www.baodu.com");

        //配置请求信息
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(500)//设置获取连接的最长时间
                .setConnectTimeout(1000)//设置获取连接的最长时间,单位是毫秒
                .setSocketTimeout(10 * 100)//设置数据传输的最长时间
                .build();

        //给请求色泽请求信息
        httpGet.setConfig(config);

        CloseableHttpResponse response = null;
        try {
            //使用httpGet发起请求,获取response对象
            response = httpClient.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(),
                        "utf8");
                System.out.println(content);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值