Android模拟登陆带验证码的网站客户端

http://www.eoeandroid.com/home.php?mod=space&uid=816376&do=blog&id=47964

Android模拟登陆带验证码的网站客户端

基础教程 238  0
首先获取验证码并保存Cookie,登陆时将Cookie和账号密码一同发送出去,返回状态码200,登陆成功,接下来再去访问其他需要登录权限的页面时附上Cookie发送出去即可。

要实现模拟登陆,首先需要了解登陆网站时请求中都包含什么信息, 需要用到的工具是 HttpWatch ,这是抓包需要的工具,然后还有一个jar包,叫 Jsoup ,这是用来解析网页HTML代码的。其次要用到抓取网页的类HttpClient。

要登录的网站为http://city.dlut.edu.cn/
登陆页面为http://cityjw.dlut.edu.cn:7001/ACTIONLOGON.APPPROCESS

通过 HttpWatch可以看到

POST的数据为账号 密码 验证码 和两个无关的坐标数据
查看Cookies选项可以查看到Cookie

现在我们已经知道了我们POST的数据是什么,接下来便可以开工敲代码了。

首先获得验证码
public Bitmap getcode() throws Exception {
 HttpPost httpPost = new HttpPost("http://cityjw.dlut.edu.cn:7001/ACTIONVALIDATERANDOMPICTURE.APPPROCESS");
 HttpResponse httpResponse = client.execute(httpPost);
 COOKIE = ((AbstractHttpClient) client).getCookieStore().getCookies().get(0).getValue();
 byte[] bytes = EntityUtils.toByteArray(httpResponse.getEntity()); 
 Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); 
 return bitmap; 
 }

然后将Cookie和账号密码一同加入到请求,发送给网站服务器
public String login(String name, String psw, String code) {
 HttpResponse httpResponse; String uriAPI = "http://cityjw.dlut.edu.cn:7001/ACTIONLOGON.APPPROCESS"; 
  建立HTTP Post连线  
HttpPost httpRequest = new HttpPost(uriAPI); 
 List<NameValuePair> params = new ArrayList<NameValuePair>();
 String result = null; 
 params.add(new BasicNameValuePair("Agnomen", code));
 params.add(new BasicNameValuePair("Password", psw)); 
 params.add(new BasicNameValuePair("submit.x", "25"));
 params.add(new BasicNameValuePair("submit.y", "6"));
 params.add(new BasicNameValuePair("WebUserNO", name));
 httpRequest.setHeader("Cookie", "JSESSIONID=" + COOKIE); 
 try { 
 // 发出HTTP 
request httpRequest.setEntity(new UrlEncodedFormEntity(params, "GBK")); 
 // 取得HTTP response httpResponse = client.execute(httpRequest); // 执行
 // 若状态码为200 ok
 if (httpResponse.getStatusLine().getStatusCode() == 200) { // 返回值正常
 StringBuffer sb = new StringBuffer(); 
 HttpEntity entity = httpResponse.getEntity();
 String content = EntityUtils.toString(entity);
 InputStream is = entity.getContent(); 
 BufferedReader br = new BufferedReader(new InputStreamReader(is, "GBK"));
 String data = "";
 while ((data = br.readLine()) != null)
 { 
 sb.append(data); 
 } 
 result = sb.toString(); // 此时result中就是登陆后的页面的HTML的源代码了
 } 
else { 
 }
 } 
catch (Exception e) 
 e.printStackTrace(); 
 } 
 return result; 
 }

该方法返回的字符串为登陆后的页面源码
提取页面有用信息可以使用Jsoup,正则表达式也可以,不过相对麻烦一点

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值