Java登陆带验证码的网站

  一个项目需要登陆一个网站,原来以为挺简单的 , 不就是post个cookies上去, 但做起来才发现没那么简单。给那个验证码折腾了两了。 

  获取验证码有两条路可以走,一个是OCR识别技术,另一个是下载到本机自己手动输。这里分享的第二种。

  下载验证码方法有很多,可以通过把路径写进URl,通过.openConnection 获取输入流。但这种获取的验证码与后来post所需的不是同一个。

因为post的时候又new 一次Url 可把图像给更新了,刚才所获取的不就是白费了。所以需要引入新的jar包org.apache.commons.httpclient.jar,用到 httpClient,整个过程只new 了一次 httpclient,就相当于整个过程只用了一个客户端 ,post的时候 图片没更新!好了,上马!

  HttpClient client = new HttpClient();
client.getHostConfiguration().setHost(LOGON_SITE, LOGON_PORT);
PostMethod post = new PostMethod(
"http://ceshi.zeyu.org/include/vdimgck.php");// 验证码的相对路径,从源代码看出来就行了
client.executeMethod(post);


InputStream is = post.getResponseBodyAsStream();
BufferedImage image = ImageIO.read(is);
File file = new File("D:/image");
if (!file.isDirectory()) {
file.mkdir();
}
File imgCodeFile = new File("D:\\image\\" + System.currentTimeMillis()
+ ".gif");
ImageIO.write(image, "gif", imgCodeFile);
Scanner sc = new Scanner(System.in);
System.out.print("验证码在D:\\image目录下 ,请你查看并输入:");
String inputCode = sc.next();
System.out.println("验证码为" + inputCode);

                // post.releaseConnection();//释放连接


这样,验证码就下到指定路径了。接着是post了。之前不得不介绍一个抓包软件httpwatch

 

随便输几个进去,按登陆,就看出了post了哪些数据了。我们直接把他们post上就行了。

PostMethod post1 = new PostMethod(LOGON_SITE);//这里输入post去的那个网站


NameValuePair adminstyle = new NameValuePair("adminstyle", "newdedecms");
NameValuePair dopost = new NameValuePair("dopost", "login");
NameValuePair gotopage = new NameValuePair("gotopage", "");
NameValuePair pwd = new NameValuePair("pwd", "·····");
NameValuePair userid = new NameValuePair("userid", "·····");
NameValuePair validate = new NameValuePair("validate", inputCode);


post1.setRequestBody(new NameValuePair[] { adminstyle, dopost,
gotopage, pwd, userid, validate });
client.executeMethod(post1);

//这个时候也就获得的cookies了,以后用它登陆就行了,不过存活期只有7天

//查看cookies

Cookie[] cookies = client.getState().getCookies();
for (Cookie cookie : cookies) {
String name = cookie.getName();
String value = cookie.getValue();
System.out.println(name + "      " + value);
}

    client.getState().addCookies(cookies); //让客户端添加cookies

//查看结果

    String responseString = new String(post1.getResponseBodyAsString()
 .getBytes("gbk"));
 System.out。println("=========================登录页面===========================");
System.out.println(responseString);

//最后释放资源

                post.releaseConnection();
post1.releaseConnection();

 大功告成!






  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值