轻松把玩HttpClient之封装HttpClient工具类(五),携带Cookie的请求

x33g5p2x  于2021-12-28 转载在 其他  
字(2.9k)|赞(0)|评价(0)|浏览(286)

     最近更新了一下HttpClientUtil工具类代码,主要是添加了一个参数HttpContext,这个是用来干嘛的呢?其实是用来保存和传递Cookie所需要的。因为我们有很多时候都需要登录,然后才能请求一些想要的数据。而在这以前使用HttpClientUtil工具类,还不能办到。现在更新了以后,终于可以了。

     先说一下思路:本次的demo,就是获取csdn中的c币,要想获取c币,必须先登录。而每次登录需要5个参数。其中2个必不可少的参数是用户名和密码,其他的3个参数,是需要从登录页面获取的。在第一次请求登录页面,只要设置了CookieStore,就可以自动获取cookie了,然后从返回的html源码中获取参数,再组装添加用户名密码,然后第二次登录,如果返回的html源码中有“帐号登录”这几个字,就说明登录失败了。否则登录成功。可以打印一下cookie(已注释)。然后再访问c币查询的页面,就可以从返回的html源码中解析到c币的值了。登录时需要注意的是:直接提交用户名密码或者第二次登录不携带context参数,是不能登录成功的。

     具体代码如下:

public static void main(String[] args) throws HttpProcessException {
		//登录地址
		String loginUrl = "https://passport.csdn.net/account/login";
		//C币查询
		String scoreUrl = "http://my.csdn.net/my/score";
		
		HttpClientContext context = new HttpClientContext();
		CookieStore cookieStore = new BasicCookieStore();
		context.setCookieStore(cookieStore);
		//获取参数
		String loginform = HttpClientUtil.send(loginUrl, context);
//		System.out.println(loginform);
		System.out.println("获取登录所需参数");
		String lt = regex("\"lt\" value=\"([^\"]*)\"", loginform)[0];
		String execution = regex("\"execution\" value=\"([^\"]*)\"", loginform)[0];
		String _eventId = regex("\"_eventId\" value=\"([^\"]*)\"", loginform)[0];
		
		//组装参数
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", "用户名");
		map.put("password", "密码");
		map.put("lt", lt);
		map.put("execution", execution);
		map.put("_eventId", _eventId);

		//发送登录请求
		String result = HttpClientUtil.send(loginUrl, map, context);
//		System.out.println(result);
		if(result.contains("帐号登录")){//如果有帐号登录,则说明未登录成功
			String errmsg = regex("\"error-message\">([^<]*)<", result)[0];
			System.err.println("登录失败:"+errmsg);
			return;
		}
		System.out.println("----登录成功----");
		
//		//打印参数,可以看到cookie里已经有值了。
//		cookieStore = context.getCookieStore();
//		for (Cookie cookie : cookieStore.getCookies()) {
//			System.out.println(cookie.getName()+"--"+cookie.getValue());
//		}
		
		//访问积分管理页面
		Header[] headers = HttpHeader.custom().userAgent("Mozilla/5.0").build();
		result = HttpClientUtil.send(scoreUrl, headers, context);
		//获取C币
		String score = regex("\"last-img\"><span>([^<]*)<", result)[0];
		System.out.println("您当前有C币:"+score);
		
	}

       从html源码中解析参数和c币值所用到的一个方法:

/**
	 * 通过正则表达式获取内容
	 * 
	 * @param regex		正则表达式
	 * @param from		原字符串
	 * @return
	 */
	public static String[] regex(String regex, String from){
		Pattern pattern = Pattern.compile(regex); 
		Matcher matcher = pattern.matcher(from);
		List<String> results = new ArrayList<String>();
		while(matcher.find()){
			for (int i = 0; i < matcher.groupCount(); i++) {
				results.add(matcher.group(i+1));
			}
		}
		return results.toArray(new String[]{});
	}

       测试结果:

     最重要的就是context这个参数了,给它设置了cookiestore,那么会在每次请求时将cookie带入请求中。或者也可以在header中手动设置cookie参数,也是可以做到的。

     代码都已经提交至:https://github.com/Arronlong/httpclientUtil

       httpclientUtil (QQ交流群:548452686 


相关文章