1. 程式人生 > >帶cookie訪問伺服器實現模擬登入

帶cookie訪問伺服器實現模擬登入

當我們需要抓取需要登入的網站的資訊或者實現模擬登入時,我們需要得到第一次登入網站的cookie,以便於下次登入可以不用post引數實現登入,只要將cookie放入標頭檔案就好,這是之前寫的模擬登入學校教務的程式碼,記錄以便查閱。

public String DoLogin(final String user, final String password, final String verifation) {

                DefaultHttpClient   defaultclient = new DefaultHttpClient();  

                //設定post引數
List<NameValuePair> params = new ArrayList<NameValuePair>(); params.add(new BasicNameValuePair("groupId", "")); params.add(new BasicNameValuePair("j_username", user)); params.add(new BasicNameValuePair("j_password", password)); params
.add(new BasicNameValuePair("j_captcha", verifation)); params.add(new BasicNameValuePair("login", "登入")); //獲得個人主介面的HTML try { HttpPost httpPost = new HttpPost(LOGINURL); System.out.println(LOGINURL); httpPost.setHeader("Cookie"
, Cookie); HttpResponse httpResponse; httpPost.setEntity((HttpEntity) new UrlEncodedFormEntity(params, HTTP.UTF_8)); httpResponse = defaultclient.execute(httpPost); httpPost.setHeader("Cookie", Cookie); System.out.println(Cookie); if (httpResponse.getStatusLine().getStatusCode() == 200) { StringBuffer sb = new StringBuffer(); HttpEntity entity = httpResponse.getEntity(); MAINBODYHTML = EntityUtils.toString(entity); } if(httpResponse.getStatusLine().getStatusCode() == 302){ String locationUrl=httpResponse.getLastHeader("Location").getValue(); System.out.println(locationUrl); LOGINURL=locationUrl; System.out.println("302"); DoLogin(user, password, verifation); } else{ StringBuffer sb = new StringBuffer(); HttpEntity entity = httpResponse.getEntity(); MAINBODYHTML = EntityUtils.toString(entity); System.out.println( MAINBODYHTML); } } catch (UnsupportedEncodingException e) { System.out.println("驗證碼不正確"); e.printStackTrace(); } catch (ClientProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } LOGINURL="http://jw.djtu.edu.cn/academic/j_acegi_security_check"; return MAINBODYHTML; }