HttpClient爬虫登录类模板

这篇博客介绍了如何封装一个通用的爬虫模板,包括mypachong接口和mypachongimpl抽象类。mypachong接口定义了登录和HTTP请求方法,而mypachongimpl抽象类提供了默认的GET和POST请求实现,通过登录获取的cookieStore来创建HttpClient。这样,后续的爬虫类只需实现login方法,就能完成基本的网页操作。
摘要由CSDN通过智能技术生成

因为最近编写需要登录类的爬虫比较多,所以想封装一个使用的模板,方便以后编写

继承结构

interface mypachong
----abstract mypachongimpl

介绍

mypachong接口,描述了一个爬虫程序需要一个login的方法实现登录操作,并封装get,post请求(未将方法设置未static是考虑到后续多用户爬取时,其实现类可以封装成员变量描述,不同用户信息)

public interface mypachong {
	boolean login();//登录
	HttpResponse get(String url,Map<String,String> map) ;//get
	HttpResponse post(String url,Map<String,String> map);//post
}

mypachong的抽象子类,封装默认的post和get.后续使用只需继承并实现login,即可完成浏览网站的基本操作(post,get),防止出现代码繁多

public abstract class mypachongimpl implements mypachong {
	public CookieStore cookieStore = null;
	public HttpResponse get(String url, Map<String, String> map) {
		//未登录时跑去执行login
		while(cookieStore == null)
			login();
			//根据登录获取的cookieStore创建Htttpclient
		HttpClient httpclient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
		String geturl = url;
		//添加参数
		if (map != null)
			for (Map.Entry<String, String> entry : map.entrySet()) {
				geturl += "&" + entry.getKey() + "=" + entry.getValue();
			}
		HttpGet get = new HttpGet(geturl);
		HttpResponse response = null;
		try {
			response = httpclient.execute(get);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
	public HttpResponse post(String url, Map<String, String> map) {
	//未登录时跑去执行login
		while(cookieStore == null)
			login();
			//根据登录获取的cookieStore创建Htttpclient
		HttpClient httpclient = HttpClientBuilder.create().setDefaultCookieStore(cookieStore).build();
		String posturl = url;
		HttpPost post = new HttpPost(posturl);
			//添加参数
		if (map != null) {
			List<NameValuePair> formlist = new ArrayList<NameValuePair>();
			for (Map.Entry<String, String> entry : map.entrySet()) {
				formlist.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
			try {
				UrlEncodedFormEntity urlEncodedFormEntity = new UrlEncodedFormEntity(formlist, "UTF-8");
				post.setEntity(urlEncodedFormEntity);
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			}
		}
		HttpResponse response = null;
		try {
			response = httpclient.execute(post);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return response;
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值