手拉手Java爬虫HttpClient

举报
QGS 发表于 2024/03/22 21:57:27 2024/03/22
【摘要】 手拉手Java爬虫HttpClient

JAVA爬虫

HttpClient

HttpClient 是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议。

 

Pom.xml添加依赖

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

GET请求

不带参

public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpGet);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取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 {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

 

带参

public static void main(String[] args) throws Exception {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//设置带参的url地址http://yun.itheima.com/search?keys=java
URIBuilder uriBuilder =new URIBuilder("http://yun.itheima.com/search");
uriBuilder.setParameter("keys","java");

//创建HttpGet对象,设置url
HttpGet httpGet =new HttpGet(uriBuilder.build());
System.out.println("发起请求信息:"+httpGet);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取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 {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

 

POST请求

不带参


public static void main(String[] args) {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
System.out.println("发起请求信息:"+httpPost);

CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取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 {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

 

带参

public static void main(String[] args) throws UnsupportedEncodingException {
//创建HttpClient对象
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建httpPost对象,设置url
HttpPost httpPost = new HttpPost("http://yun.itheima.com/search");
System.out.println("发起请求信息:"+httpPost);
//声明list集合,封装表单中的参数
List<NameValuePair> params =new ArrayList<NameValuePair>();
//设置带参的url地址http://yun.itheima.com/search?keys=java
params.add(new BasicNameValuePair("keys","java"));
//创建表单的Entity对象
UrlEncodedFormEntity formEntity =new UrlEncodedFormEntity(params,"utf8");
//设置表单的Entity对象到Post请求中
httpPost.setEntity(formEntity);


CloseableHttpResponse response = null;
try {
//创建HttpClient发起请求,获取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 {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}

}
}

 

 

连接池

public static void main(String[] args) {
PoolingHttpClientConnectionManager cm =new PoolingHttpClientConnectionManager();
//设置连接数
cm.setMaxTotal(100);
//设置没个主机的最大连接数
cm.setDefaultMaxPerRoute(10);

doGet(cm);
}

private static void doGet(PoolingHttpClientConnectionManager cm) {
CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
HttpGet httpGet =new HttpGet("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#auto/zh/");
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 {
//关闭response
try {
response.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
//关闭httpClient
try {
httpClient.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}

 

连接请求配置

//配置请求信息
//setConnectTimeout创建连接的最长时间,毫秒 、setConnectionRequestTimeout获取连接的最长时间,毫秒
RequestConfig config =RequestConfig.custom().setConnectTimeout(1000).setConnectionRequestTimeout(1000).build();

httpGet.setConfig(config);

 

Jsoup解析

Jsoup是一款Java的HTML解析器,可直接解析某个URL地址、HTML文本内容。它提供了一套非常省力的AP,可通过DOM,CSs以及类似于 Jquery的操作方法来取出和操作数据。

 

jsoup的主要功能如下:“1.从一个URL,文件或字符串中解析HTML;2.使用DOM或CSS选择器来查找、取出数据;3.可操作HTML元素、属性、I文目;

 

maven加入依赖

<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.14.2</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>

Jsoup解析Url

@Test
public void JUrl()throws Exception{
//解析url地址,参数1:要访问的url,参数2:访问超时时间
Document doc = Jsoup.parse(new URL("https://fanyi.baidu.com/translate?aldtype=16047&query=&keyfrom=baidu&smartresult=dict&lang=auto2zh#zh/en/"), 100000);
//使用标签选择器
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);
}

 

Jsoup解析文件

//解析文件
Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\比较数字大小.html"),"utf8");
String text = doc.getElementsByTag("title").first().text();
System.out.println(text);

 

Dom方式获取元素

元素获取

1.根据d查询元素 getElementByld

2.根据标签获取元素 getElementsByTag

3.根据 class i获取元素 getElementsByClass

4.根据属性获取元素 getElementsByAttribute

@Test
public void DOMGet()throws Exception{
//解析文件
Document doc = Jsoup.parse(new File("F:\\front\\code\\vue01\\domdiff算法.html"),"utf8");
//1.根据d查询元素 getElementById
Element elementById = doc.getElementById("101");
System.out.println("获取到文件内容:"+elementById.text());
//2.根据标签获取元素 getElementsByTag
Element th = doc.getElementsByTag("th").first();
System.out.println("获取到文件内容:"+th.text());
//3.根据 class i获取元素 getElementsByClass
Elements abc = doc.getElementsByClass("abc");
System.out.println("获取到文件内容:"+abc.text());
//4.根据属性获取元素 getElementsByAttribute
Elements id = doc.getElementsByAttribute("id");
System.out.println(id.text());
Elements id1 = doc.getElementsByAttributeValue("id", "101");
System.out.println(id1.text());
}

 

 

 

 

 

 

 

 

 

 

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。