android/java類比登入正方教務系統

來源:互聯網
上載者:User

標籤:驗證碼   private   android   Google瀏覽器   成都大學   

    最近閑來無事,打算開始寫部落格,也算是對自己知識的一個總結。本篇將講解如何使用HttpClient類比登入正方教務系統。

    需要使用道德jar包:HttpClient,Jsoup.(下載jar包)

    本次類比登入的成都大學的教務系統,其他學校的教務系統,可參照本文給出的流程和代碼進行修改並測試。

    基本流程:

    1).使用Google瀏覽器開啟教務系統首頁,並開啟瀏覽器開發人員工具記錄瀏覽過程,然後正常登入並瀏覽自己的課表,成績等資訊。

    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";// 進入教務系統首頁擷取的Cookieprivate 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就是用HttpPostHttpGet getMainUrl = new HttpGet(mainUrl);//通過調用HttpClient的execute(HttpRequestBase)方法獲得HttpResponse執行個體HttpResponse response = httpClient.execute(getMainUrl);//擷取Cookiecookie = 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,image/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解析成Stringpublic 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;}}


本文出自 “淺夢薄涼” 部落格,請務必保留此出處http://lovexiaoyang.blog.51cto.com/10006124/1885933

android/java類比登入正方教務系統

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.