HttpUtils-----httpclient爬虫

获取更多内容

获取更多内容请访问: https://juntech.top/

将httpclient爬虫功能封装在httpUtils类里面:

httpUtils.java

创建连接池管理器

package top.juntech.autohome.utils;

import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Configuration;

@Configuration
public class HttpUtils {
//    编写连接池管理器
    public PoolingHttpClientConnectionManager pm(){
//        创建连接池管理器
        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
//        设置最大连接数
        cm.setMaxTotal(200);
//        设置最大连接主机数
        cm.setDefaultMaxPerRoute(20);
//        关闭失效连接
        cm.closeExpiredConnections();
//        返回连接池
        return cm;
    }

}

ApiService.java

进行httpclient一些功能的封装:下载图片和解析html

package top.juntech.autohome.service.impl;

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 org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.juntech.autohome.service.ServiceApi;
import top.juntech.autohome.utils.HttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.UUID;

@Service
public class ApiServiceImpl implements ServiceApi {
    @Autowired
    private HttpUtils httpUtils;


    @Override
    public String getHtml(String uri) {
//        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(httpUtils.pm()).build();
        HttpGet httpGet = new HttpGet();
        httpGet.setHeader("User-Agen","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.19 Safari/537.36");
        httpGet.setConfig(this.getRequestConfig());
        CloseableHttpResponse response = null;
        try {
            response = client.execute(httpGet);
            if(response.getStatusLine().getStatusCode() == 200){
                String html = "";
                if(response.getEntity() != null){
                    html = EntityUtils.toString(response.getEntity(), "utf8");
                    System.out.println(html);

                }
                return html;
            }
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                //关闭resp
                response.close();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

//下载图片
    @Override
    public String getImg(String uri) {
        CloseableHttpClient client = HttpClients.custom().setConnectionManager(httpUtils.pm()).build();
        HttpGet httpGet = new HttpGet();
        httpGet.setHeader("User-Agen","Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.19 Safari/537.36");
        httpGet.setConfig(this.getRequestConfig());
        CloseableHttpResponse response = null;

        try {
            response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
               String contentType = response.getEntity().getContentType().getValue();
               String extname = contentType.split("/")[1];
                //        使用UUID生成图片名
                UUID uuid = UUID.randomUUID();
                String imageName = uuid.toString() + extname;
                //声明输出的文件
                OutputStream outputStream = new FileOutputStream(new File("C:\\Users\\Ryan\\Downloads\\images\\"+imageName));
//                输出文件
                response.getEntity().writeTo(outputStream);
//                返回imageName
                return imageName;

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                //关闭resp
                response.close();

            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;
    }

//超时配置
    public RequestConfig getRequestConfig(){
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(10000)
                .setConnectTimeout(500)
                .setConnectionRequestTimeout(1000).build();
        return requestConfig;
    }
}

更多详情

设置为vip可见的都可访问下面链接地址,即可观看原文
更多详情请访问: juntech

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 前言 超文本传输协议(HTTP)也许是当今互联网上使用的最重要的协议了。Web服务,有网络功能的设备和网络计算的发...
    狂奔的蜗牛_wxc阅读 5,542评论 0 12
  • 随着互联网+时代的来临,越来越多的互联网企业层出不穷,涉及游戏、视频、新闻、社交、电商、房产、旅游等众多行业。如今...
    JackChen1024阅读 10,754评论 2 49
  • 培训计划: 爬虫的概念 网络爬虫(又被称为网页蜘蛛,网络机器人,在FOAF社区中间,更经常的称为网页追逐者),是一...
    蜻蜓小子阅读 1,803评论 0 0
  • 原文链接 第1章:基础 1.1. 执行请求 HttpClient最重要的功能是执行HTTP方法。 执行HTTP方法...
    王德培阅读 2,373评论 0 3
  • 第二章 连接管理 HttpClient有一个对连接初始化和终止,还有在活动连接上I/O操作的完整控制。而连接操作的...
    狂奔的蜗牛_wxc阅读 1,193评论 0 0