初识HttpClient,自己尝试写了个工具类

作为一名即将毕业的大四学生,真正的学习是从今年过年时开始的,为了做毕业设计,疫情期间在家自学了SSM框架,在这段期间我才感觉到敲代码也是一件不错的事情,但还是没有做笔记的习惯。直到今天,我有一个知识点想不起来,翻看以前学习的视频差不多一个小时才找到。这时我才明白了做笔记的重要性!好了,闲话不多说,开始今天的笔记。

初识HttpClient后,觉得这个可能需要一个工具类来方便之后的学习,所以记录一下自己尝试写的一个工具类

maven的pom依赖
<dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.2</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!--解析html-->
        <dependency>
            <groupId>org.jsoup</groupId>
            <artifactId>jsoup</artifactId>
            <version>1.11.3</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <!-- 包含StringUtils,处理字符串的 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.6</version>
        </dependency>
    </dependencies>
工具类 只写了get和post,随着深入学习再补充
/**
 * HttpClient工具类
 */
public class HttpClientUtils {
    //统一使用的编码
    private static final String Encoding = "UTF-8";
    //连接池对象的一些属性
    private static final int MaxTotal = 100;//最大连接数
    private static final int DefaultMaxPerRoute = 10; //每个主机的最大连接数
    //请求的一些配置信息config
    private static final int ConnectTimeout = 1000;//创建连接最长时间
    private static final int ConnectionRequestTimeout = 1000;//获取连接的最长时间
    private static final int SocketTimeout = 10 * 1000;//数据传输的最长时间
    private static PoolingHttpClientConnectionManager pcm;

    /**
     * 补充知识
     * 创建对象的过程总结:
     * 1、将要创建的对象所属的类,加载到方法区
     * 2、在栈内存中,创建该类型的引用
     * 3、在堆内存中,开辟一块存储空间,用于存储该对象的数据
     * 4、默认初始化赋值
     * 5、显式初始化赋值
     * 6、构造方法初始化赋值
     * 7、将对象的地址,赋值给栈内存中的引用
     */
    //构造方法
    private HttpClientUtils() {
        //连接池对象
        pcm = new PoolingHttpClientConnectionManager();
        //顺便设置以下连接池的相关属性
        pcm.setMaxTotal(MaxTotal);
        pcm.setDefaultMaxPerRoute(DefaultMaxPerRoute);
    }

    /**
     * get方式获取页面,无header,无参数
     *
     * @param uri
     * @return
     */
    public static String doGetToFindHtml(String uri) throws Exception {
        return doGetToFindHtml(uri, null, null);
    }

    /**
     * get方式获取页面,有header,无参数
     *
     * @param uri
     * @param header
     * @return
     * @throws Exception
     */
    public static String doGetToFindHtml(String uri, Map<String, String> header) throws Exception {
        return doGetToFindHtml(uri, header, null);
    }

    /**
     * get方式获取页面       全
     *
     * @param url
     * @param params
     * @return
     */
    public static String doGetToFindHtml(String url, Map<String, String> header, Map<String, String> params) throws Exception {
        //创建HttpClient对象,使用连接池
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();
        //根据参数去 将链接 去处理好 为链接加 params的格式
        URIBuilder uriBuilder = new URIBuilder(url); //将基础url放入
        //如果请求参数params不为空就可以开始拼接了
        if (params != null) {
            //遍历map集合
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        URI buildSuccess = uriBuilder.build();//构建好的链接
        //创建HttpGet,并设置地址
        HttpGet httpGet = new HttpGet(buildSuccess);
        //设置配置信息和设置请求信息
        RequestConfig requestConfig = RequestConfig.custom()  //用builder创建
                .setConnectTimeout(ConnectTimeout)
                .setSocketTimeout(SocketTimeout)
                .setConnectionRequestTimeout(ConnectionRequestTimeout)
                .build();
        httpGet.setConfig(requestConfig);
        //header不为空设置请求头  自定义方法封装Header到httpGet中
        if (header != null) {
            SetHeader(header, httpGet);
        }
        CloseableHttpResponse response = null;
        try {
            //用httpClient发起响应
            response = httpClient.execute(httpGet);
            //状态码为200的时候,解析响应结果,返回String
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(response.getEntity(), Encoding);
                return resultString;//返回String
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ""; //请求失败,或者状态码不为200,返回空串
    }

    /**
     * 将请求头设置到请求中
     *
     * @param header
     * @param httpAll
     */
    private static void SetHeader(Map<String, String> header, HttpRequestBase httpAll) {
        Set<Map.Entry<String, String>> entrySet = header.entrySet();
        for (Map.Entry<String, String> entry : entrySet) {
            httpAll.setHeader(entry.getKey(), entry.getValue());
        }
    }


    /**
     * Post方式获取页面       全
     *
     * @param url
     * @param params
     * @return
     */
    public static String doPostToFindHtml(String url, Map<String, String> header, Map<String, String> params) throws Exception {
        //创建HttpClient对象,使用连接池
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(pcm).build();
        //根据参数去 将链接 去处理好 为链接加 params的格式
        URIBuilder uriBuilder = new URIBuilder(url); //将基础url放入
        //如果请求参数params不为空就可以开始拼接了
        if (params != null) {
            //遍历map集合
            Set<Map.Entry<String, String>> entrySet = params.entrySet();
            for (Map.Entry<String, String> entry : entrySet) {
                uriBuilder.setParameter(entry.getKey(), entry.getValue());
            }
        }
        URI buildSuccess = uriBuilder.build();//构建好的链接
        //创建HttpGet,并设置地址
        HttpPost httpPost = new HttpPost(buildSuccess);
        //设置配置信息和设置请求信息
        RequestConfig requestConfig = RequestConfig.custom()  //用builder创建
                .setConnectTimeout(ConnectTimeout)
                .setSocketTimeout(SocketTimeout)
                .setConnectionRequestTimeout(ConnectionRequestTimeout)
                .build();
        httpPost.setConfig(requestConfig);
        //header不为空设置请求头  自定义方法封装Header到httpGet中
        if (header != null) {
            SetHeader(header, httpPost);
        }
        CloseableHttpResponse response = null;
        try {
            //用httpClient发起响应
            response = httpClient.execute(httpPost);
            //状态码为200的时候,解析响应结果,返回String
            if (response.getStatusLine().getStatusCode() == 200) {
                String resultString = EntityUtils.toString(response.getEntity(), Encoding);
                return resultString;//返回String
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ""; //请求失败,或者状态码不为200,返回空串
    }

    /**
     * get方式获取页面,无header,无参数
     *
     * @param uri
     * @return
     */
    public static String doPostToFindHtml(String uri) throws Exception {
        return doPostToFindHtml(uri, null, null);
    }

    /**
     * get方式获取页面,有header,无参数
     *
     * @param uri
     * @param header
     * @return
     * @throws Exception
     */
    public static String doPostToFindHtml(String uri, Map<String, String> header) throws Exception {
        return doPostToFindHtml(uri, header, null);
    }

}
测试方法
public class UtilsTest {
    @Test
    public void test1() throws Exception {
        //声明需要解析的初始地址
        String url="*********";
        String html = HttpClientUtils.doGetToFindHtml(url);
        System.out.println(html);
    }
    @Test
    public void test2() throws Exception {
        //声明需要解析的初始地址
        String url="******";
        Map<String, String> header = new HashMap<String, String>();
        header.put("Accept", "*******");
        header.put("Accept-Language", "*******");
        header.put("Connection", "*******");
        header.put("cookie", "******");
        header.put("user-agent", "********");
        header.put("referer", "*******");

        String html = HttpClientUtils.doGetToFindHtml(url, header);
        System.out.println(html);
        //用Jsoup解析获取登陆状态
        Document document = Jsoup.parse(html);
        System.out.println("-----------------------------------------------------------");
        System.out.println(document.select("button#regist_button").first().text());
    }
希望各位看见文章的有缘人,可以给在下代码中的不足予以批评指正,万分感谢。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值