最近闲来无事,打算开始写博客,也算是对自己知识的一个总结。本篇将讲解如何使用HttpClient模拟登录正方教务系统。
需要使用道德jar包:HttpClient,Jsoup.(下载jar包)
本次模拟登录的成都大学的教务系统,其他学校的教务系统,可参照本文给出的流程和代码进行修改并测试。
基本流程:
1).使用谷歌浏览器打开教务系统首页,并打开浏览器开发者工具记录浏览过程,然后正常登录并浏览自己的课表,成绩等信息。
2).下载jar包,将jar引用到自己需要的项目中,可创建一个新的工具类。
3).创建HttpClient实例,接着创建HttpRequestBase实例,接着调用HttpClient.execute()的方法获取HttpResponse实例。得到验证码图片及其他数据。
测试代码:
public class LoginUtil { // 教务系统首页 private String mainUrl = "http://202.115.80.153/"; // 验证码获取页面 private String checkCodeUrl = "http://202.115.80.153/CheckCode.aspx"; // 验证码图片保存路径 private String checkCodeDes = "C:\\Users\\linYang\\Desktop"; // 登陆页面 private String loginUrl = "http://202.115.80.153/default2.aspx"; // 进入教务系统首页获取的Cookie private String cookie = ""; // 学生学号 private String stuNo = "201210411122"; // 教务系统密码,为保护隐私,现将密码隐藏 private String password = "******"; // 教务系统对应的学生姓名 private String realName = ""; // 登录成功后,重定向的页面 private String contentUrl = "http://202.115.80.153/xs_main.aspx?xh=" + stuNo; // 获取课程的页面 private String courseUrl = "http://202.115.80.153/xskbcx.aspx?xh=" + stuNo; // 课程编号 private String courseNo = "gnmkdm=N121603"; // 成绩编号 private String soureNo = ""; // HttpClient对象 private HttpClient httpClient = null; public void scanMainUrl() throws Exception { httpClient = HttpClients.createDefault(); //根据浏览器个记录,是GET方法就使用HttpGet,是POST就是用HttpPost HttpGet getMainUrl = new HttpGet(mainUrl); //通过调用HttpClient的execute(HttpRequestBase)方法获得HttpResponse实例 HttpResponse response = httpClient.execute(getMainUrl); //获取Cookie cookie = response.getFirstHeader("Set-Cookie").getValue(); //输出Cookie的值到控制台 System.out.println(cookie); //将HTML网页解析成String,方便获取Form中隐藏的参数以及需要的元素的信息 String tempHtml = parseToString(response); //构造需要查询元素的集合 List<QueryEntity> keyWords = new ArrayList<QueryEntity>(); //添加查询元素信息,这里新定义了一个实例类 keyWords.add(new QueryEntity("input[name=__VIEWSTATE]", "val", null)); //获取查询信息集合 List<String> values = getValuesByKeyWords(tempHtml, keyWords); //获取验证码图片 getMainUrl = new HttpGet(checkCodeUrl); response = httpClient.execute(getMainUrl); //将验证码请求返回流解析成图片保存到桌面,开发人员也可根据需要可申请API直接编程获取验证码字符串 parseIsToImage(response.getEntity().getContent()); //调用登录方法进行登录操作 login(values, httpClient, response); } public void login(List<String> values, HttpClient httpClient, HttpResponse response) throws Exception { System.out.println("请输入验证码:"); //扫描输入获的验证码 Scanner scanner = new Scanner(System.in); String checkCode = scanner.nextLine(); //创建一个HttpPost实例,进行模拟登录操作 HttpPost httpPost = new HttpPost(loginUrl); //设置HttpPost的头信息 httpPost.addHeader("Cookie", cookie); httpPost.addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,p_w_picpath/webp,*/*;q=0.8"); httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded"); httpPost.addHeader("Referer", mainUrl); List<NameValuePair> requestEntity = new ArrayList<NameValuePair>(); requestEntity.add(new BasicNameValuePair("__VIEWSTATE", values.get(0))); requestEntity.add(new BasicNameValuePair("txtUserName", stuNo)); requestEntity.add(new BasicNameValuePair("TextBox2", password)); requestEntity.add(new BasicNameValuePair("txtSecretCode", checkCode)); requestEntity.add(new BasicNameValuePair("RadioButtonList1", "%D1%A7%C9%FA")); requestEntity.add(new BasicNameValuePair("Button1", "")); requestEntity.add(new BasicNameValuePair("lbLanguage", "")); requestEntity.add(new BasicNameValuePair("hidPdrs", "")); requestEntity.add(new BasicNameValuePair("hidsc", "")); //设置httpPost请求体 httpPost.setEntity(new UrlEncodedFormEntity(requestEntity, "gb2312")); response = httpClient.execute(httpPost); judgeLoginSuccess(response); } /* 判断是否登录成功 */ private void judgeLoginSuccess(HttpResponse response) throws Exception { // TODO Auto-generated method stub //判断网页是否重定向,不能重定向,则需要检查参数是否遗漏,密码是否错误! if (response.getStatusLine().getStatusCode() == 302) { System.out.println("登录成功!!"); HttpGet getContent = new HttpGet(contentUrl); getContent.setHeader("Referer", mainUrl); getContent.setHeader("Cookie", cookie); response = httpClient.execute(getContent); String tempHtml = parseToString(response); System.out.println(tempHtml); List<QueryEntity> keyWords = new ArrayList<QueryEntity>(); keyWords.add(new QueryEntity("span#xhxm", "text", null)); //获取学生姓名 realName = getValuesByKeyWords(tempHtml, keyWords).get(0); getCourse(); } else { System.out.println("登录失败!!"); } } /* 获取课程页面 */ public void getCourse() throws Exception { String courseUrl1 = courseUrl + "&xm=" + realName + "&" + courseNo; HttpGet getCourse = new HttpGet(courseUrl1); getCourse.setHeader("Referer", "http://202.115.80.153/xs_main.aspx?xh=201210411122"); getCourse.setHeader("Cookie", cookie); HttpResponse response = httpClient.execute(getCourse); String temp = parseToString(response); System.out.println("\n课程页面:" + temp); } public static void main(String[] args) throws Exception { new LoginUtil().scanMainUrl(); } //将InputStream解析成图片 public void parseIsToImage(InputStream is) throws Exception { FileOutputStream fos = new FileOutputStream(new File(checkCodeDes, "CheckCode.gif")); byte[] tempData = new byte[1024]; int len = 0; while ((len = is.read(tempData)) != -1) { fos.write(tempData, 0, len); } fos.close(); is.close(); } //将HttpResponse解析成String public String parseToString(HttpResponse response) throws Exception { InputStream is = response.getEntity().getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; StringBuilder builder = new StringBuilder(); while ((line = reader.readLine()) != null) { builder.append(line + "\n"); } reader.close(); is.close(); return builder.toString(); } //传入查询集合,获取需要查询元素的值,使用java反射进行封装,简化操作 public List<String> getValuesByKeyWords(String html, List<QueryEntity> queryEntities) throws Exception { List<String> values = new ArrayList<String>(); Element body = Jsoup.parse(html).select("body").get(0); for (QueryEntity entity : queryEntities) { Element element = body.select(entity.targetSelector).get(0); Method method = null; String value = null; Class<?> clazz = element.getClass(); if (entity.methodParms == null) { method = clazz.getMethod(entity.methodName); value = (String) method.invoke(element, new Object[] {}); } else { method = clazz.getMethod(entity.methodName, new Class[] { String.class }); value = (String) method.invoke(element, new Object[] { entity.methodParms }); } //输出选择器和对应选择器的值到控制台 System.out.println(entity.targetSelector + "\t" + value); values.add(value); } return values; } } //定义查询html元素的查询体实体类,目的在于简化查询操作 class QueryEntity { String targetSelector; String methodName; String methodParms; /** * @param targetSelector 选择器 * @param methodName 获取值的方法名 * @param methodParms 方法回调参数 */ public QueryEntity(String targetSelector, String methodName, String methodParms){ this.targetSelector = targetSelector; this.methodName = methodName; this.methodParms = methodParms; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。