您好,登錄后才能下訂單哦!
最近閑來無事,打算開始寫博客,也算是對自己知識的一個總結。本篇將講解如何使用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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。