java网络爬虫入门实例——以爬取百度首页源代码为例

本文分享了使用HttpClient 3.1爬取百度首页HTML的实战经验,通过具体代码介绍了如何创建HttpClient实例、GetMethod实例及处理响应数据的方法,并附上了运行结果及乱码解决办法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

最近在自学网络爬虫,参考教材是《自己动手写网络爬虫》,使用ide为eclipse。感觉书上入门的例子有些问题,于是我参考了httpclient 3.1的文档,爬取了百度首页的html,算是一个初学者入门的东西吧,把代码和一些心得和大家分享一下。

httpclient 3.1 下载地址:http://archive.apache.org/dist/httpcomponents/commons-httpclient/3.0/

import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;

import java.io.*;

public class HttpClientTutorial {

	private static String url = "https://www.baidu.com/";
  
	public static void main(String[] args) {
		
		// Create an instance of HttpClient.
		HttpClient client = new HttpClient();
		
		// Create a method instance.
		GetMethod method = new GetMethod(url);
		
		// Provide custom retry handler is necessary
		method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler(3, false));
		
		try {
			// Execute the method.
			int statusCode = client.executeMethod(method);
			
			if (statusCode != HttpStatus.SC_OK) {
			System.err.println("Method failed: " + method.getStatusLine());
			}
			
			// Read the response body.
			byte[] responseBody = method.getResponseBody();
			
			// Deal with the response.
			// Use caution: ensure correct character encoding and is not binary data
			System.out.println(new String(responseBody));
		} catch (HttpException e) {
			System.err.println("Fatal protocol violation: " + e.getMessage());
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Fatal transport error: " + e.getMessage());
			e.printStackTrace();
		} finally {
			// Release the connection.
			method.releaseConnection();
		}
	}
}

运行结果:


如果汉字部分为乱码,则可以在window-preference-general-workspace下设置编码:


参考资料:

http://hc.apache.org/httpclient-legacy/tutorial.html 

https://zhidao.baidu.com/question/625740030659487804.html 


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值