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

       近期更新了一下HttpClientUtil工具类代码,主要是加入了一个參数HttpContext,这个是用来干嘛的呢?事实上是用来保存和传递Cookie所须要的。

由于我们有非常多时候都须要登录。然后才干请求一些想要的数据。而在这曾经使用HttpClientUtil工具类,还不能办到。如今更新了以后,最终能够了。


       先说一下思路:本次的demo,就是获取csdn中的c币,要想获取c币。必须先登录。而每次登录须要5个參数。当中2个不可缺少的參数是username和password,其它的3个參数,是须要从登录页面获取的。

在第一次请求登录页面,仅仅要设置了CookieStore,就能够自己主动获取cookie了。然后从返回的html源代码中获取參数,再组装加入usernamepassword。然后第二次登录,假设返回的html源代码中有“帐号登录”这几个字,就说明登录失败了。否则登录成功。能够打印一下cookie(已凝视)。

然后再訪问c币查询的页面,就能够从返回的html源代码中解析到c币的值了。登录时须要注意的是:直接提交usernamepassword或者第二次登录不携带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", "username");
		map.put("password", "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 httpclientUtil交流

原文地址:https://www.cnblogs.com/yfceshi/p/7365123.html