您的位置:首页 > 理论基础 > 计算机网络

httpContext使用

2016-01-07 15:03 531 查看
public class LoginCsdn {
/**
* HttpClientContext这个参数了,给它设置了cookiestore,那么会在每次请求时将cookie带入请求中。
* 或者也可以在header中手动设置cookie参数,也是可以做到的。
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
//登录地址
String loginUrl = "https://passport.csdn.net/account/login";
HttpClientContext context = new HttpClientContext();
CookieStore cookieStore = new BasicCookieStore();
context.setCookieStore(cookieStore);
//获取参数
String loginform = send(loginUrl, null, 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, String> map = new HashMap<>();
map.put("username", "");
map.put("password", "");
map.put("lt", lt);
map.put("execution", execution);
map.put("_eventId", _eventId);

//发送登录请求
String result = 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());
}

}
/**
* 通过正则表达式获取内容
*
* @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[]{});
}
public static String send(String url, Map<String, String> params,  HttpClientContext context) throws Exception{
CloseableHttpClient httpClient = HttpClientPool.getHttpClient();
HttpPost httpPost = new HttpPost(url);
if (params!=null && !params.isEmpty()) {
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Entry<String, String> param : params.entrySet()) {
list.add(new BasicNameValuePair(param.getKey(), param.getValue()));
}
//构建url加密实体,并以utf-8方式进行加密;
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list, Consts.UTF_8);
httpPost.setEntity(entity);
}
CloseableHttpResponse response = httpClient.execute(httpPost, context);
return EntityUtils.toString(response.getEntity());
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: