1、HttpClient 4.3.1 (GA)
以下列出的是 HttpClient 提供的主要的功能,要知道更多详细的功能可以参见 HttpClient 的主页。
实现了所有 HTTP 的方法(GET,POST,PUT,HEAD 等)
支持自动转向
支持 HTTPS 协议
支持代理服务器等
2、Jsoup
jsoup 的主要功能如下
从一个 URL,文件或字符串中解析 HTML
使用 DOM 或 CSS 选择器来查找、取出数据
可操作 HTML 元素、属性、文本
使用与jquery几乎一样的语法
废话不多说直接进入正题,在HTTPClient源码包内包含example文件夹此文件夹内包含一些基本用法这些例子入门足够了找到ClientFormLogin.java具体解释注释已经很清楚了大致意思就是模拟HTTP请求存储cookies。
测试网站:http://bbs.dakele.com/
因为此网站对登录做了特殊处理所以与标准的DZ
论坛可能会有些出入请自行修改
对网站的分析使用的chrome自带的审查元素,这个折腾了不少时间
登录地址:http://passport.dakele.com/login.do product=bbs
输入错误的用户名和密码会发现实际登录地址为http://passport.dakele.com/logon.do 注意【i/n的区别刚开始没注意以为见鬼了】
返回错误信息
{"err_msg":"帐号或密码错误"}
输入正确信息返回
{"result":true,"redirect":http://bbs.dakele.com/member.php mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=0&fastloginfield=username&quickforward=yes&handlekey=ls&cookietime=2592000&remember=0&username=youname&AccessKey=[]}
直接输入rediret连接和正常登录
获取跳转链接:
复制代码
private LoginResult getRedirectUrl(){
LoginResult loginResult = null;
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpost = new HttpPost(LOGINURL);
httpost.setHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
httpost.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
httpost.setHeader("Cache-Control", "max-age=0");
httpost.setHeader("Connection", "keep-alive");
httpost.setHeader("Host", "passport.dakele.com");
httpost.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
List nvps = new ArrayList ();
nvps.add(new BasicNameva luePair("product", "bbs"));
nvps.add(new BasicNameva luePair("surl", "http://bbs.dakele.com/"));
nvps.add(new BasicNameva luePair("username", "yourname"));//用户名
nvps.add(new BasicNameva luePair("password", "yourpass"));//密码
nvps.add(new BasicNameva luePair("remember", "0"));
httpost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
CloseableHttpResponse response2 = null;
try {
response2 = httpClient.execute(httpost);
if(response2.getStatusLine().getStatusCode()==200){
HttpEntity entity = response2.getEntity();
String entityString = EntityUtils.toString(entity);
JSONArray jsonArray = JSONArray.fromObject("["+entityString+"]");
JsonConfig jsonConfig=new JsonConfig();
jsonConfig.setArrayMode(JsonConfig.MODE_OBJECT_ARRAY);
jsonConfig.setRootClass(LoginResult.class);
LoginResult[] results= (LoginResult[]) JSONSerializer.toJava( jsonArray, jsonConfig );
if(results.length==1){
loginResult = results[0];
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {