搜索

java爬虫


发布时间: 2022-11-24 23:29:00    浏览次数:78 次

创建Maven工程

加入依赖

<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient -->
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
<!-- https://mvnrepository.com/artifact/org.slf4j/slf4j-log4j12 -->
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>1.7.25</version>
</dependency>

加入log4j.properties

log4j.rootLogger=DEBUG,A1
log4j.logger.cn.itcast = 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

编写代码

package com.blfsg.test;

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;

public class CrawlerTest {
    public static void main(String[] args) throws IOException {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明访问地址
        HttpGet httpGet = new HttpGet("http://www.yxans.cn");
        // 发起请求
        CloseableHttpResponse response = httpClient.execute(httpGet);
        // 判断请求是否成功
        if (response.getStatusLine().getStatusCode() == 200) {
            // 解析数据
            String content = EntityUtils.toString(response.getEntity(), "UTF-8");
            System.out.println(content);
        }
    }
}

GET请求

package com.blfsg.test;

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;

public class CrawlerGetTest {
    public static void main(String[] args) throws IOException {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明访问地址
        HttpGet httpGet = new HttpGet("http://www.yxans.cn");
        CloseableHttpResponse response = null;
        try {
            // 发送请求
            response = httpClient.execute(httpGet);
            // 判断响应码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(content.length());
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            httpClient.close();
        }
    }
}

带参数的GET请求

package com.blfsg.test;

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;
import java.net.URI;

public class CrawlerGetWithParamTest {
    public static void main(String[] args) throws Exception {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 创建URIBuilder
        URIBuilder uriBuilder = new URIBuilder("https://cn.bing.com/search");
        // 添加参数
        uriBuilder.addParameter("q","世界杯");
        // 生成访问地址
        URI uri = uriBuilder.build();
        // 创建httpGet对象
        HttpGet httpGet = new HttpGet(uri);
        CloseableHttpResponse response = null;
        try {
            // 发送请求
            response = httpClient.execute(httpGet);
            // 判断状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(content.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            httpClient.close();
        }
    }
}

POST请求

package com.blfsg.test;

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.util.EntityUtils;

import java.io.IOException;

public class CrawlerPostTest {
    public static void main(String[] args) throws IOException {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明访问地址
        HttpPost httpPost = new HttpPost("http://www.yxans.cn");
        CloseableHttpResponse response = null;
        try {
            // 发起请求
            response = httpClient.execute(httpPost);
            // 判断状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            httpClient.close();
        }
    }
}

带参数的POST的请求

package com.blfsg.test;

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.util.ArrayList;
import java.util.List;

public class CrawlerPostWithparamTest {
    public static void main(String[] args) throws Exception {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明访问地址
        HttpPost httpPost = new HttpPost("https://www.oschina.net");
        // 设置User-Agent属性,解决开源中国限制的问题
        httpPost.setHeader("User-Agent", "");
        // 设置参数
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("scope", "project"));
        params.add(new BasicNameValuePair("q", "HttpClient"));
        // 创建form表单实体
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(params, "UTF-8");
        // 设置表单到httpPost中
        httpPost.setEntity(formEntity);
        CloseableHttpResponse response = null;
        try {
            // 发起请求
            response = httpClient.execute(httpPost);

            // 判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                httpClient.close();
            }
        }
    }
}

连接池

package com.blfsg.test;

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 CrawLerPoolTest {
    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) {
        // 获取连接
        CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
        // 声明访问地址
        HttpGet httpGet = new HttpGet("http://www.yxans.cn");
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            // 判断状态码
            if (response.getStatusLine().getStatusCode() == 200) {
                String content = EntityUtils.toString(response.getEntity(), "utf-8");
                System.out.println(content.length());
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

请求参数

package com.blfsg.test;

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;

public class CrawlerParamTest {
    public static void main(String[] args) {
        // 创建httpclient
        CloseableHttpClient httpClient = HttpClients.createDefault();
        // 声明访问地址
        HttpGet httpGet = new HttpGet("http://www.yxans.cn");
        // 设置参数信息
        RequestConfig config = RequestConfig.custom().setConnectTimeout(1000) // 创建连接最大时长,单位毫秒
                .setConnectionRequestTimeout(500)   // 获取连接最大时长
                .setSocketTimeout(10 * 1000)   // 数据传输的最长时间
                .build();
        // 配置参数信息
        httpGet.setConfig(config);
        CloseableHttpResponse response = null;
        try {
            // 发起请求
            response = httpClient.execute(httpGet);

            // 判断状态码是否是200
            if (response.getStatusLine().getStatusCode() == 200) {
                // 解析数据
                String content = EntityUtils.toString(response.getEntity(), "UTF-8");
                System.out.println(content.length());
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
免责声明 java爬虫,资源类别:文本, 浏览次数:78 次, 文件大小:-- , 由本站蜘蛛搜索收录2022-11-24 11:29:00。此页面由程序自动采集,只作交流和学习使用,本站不储存任何资源文件,如有侵权内容请联系我们举报删除, 感谢您对本站的支持。 原文链接:https://www.cnblogs.com/tian0926/p/16916599.html