java類比cookie登陸操作_java

來源:互聯網
上載者:User

在使用java訪問URL時,如果該URL需要身分識別驗證,那麼就不能夠直接存取,因為沒有登陸。那麼,如何解決這個問題呢?

方法是使用java類比登陸,登陸後記錄下cookie資訊,在下次發起請求時時將cookie發送過去用以表明身份,這樣就能夠訪問帶有許可權的URL了。

下面首先介紹使用java類比登陸。 

// 串連地址(通過閱讀html原始碼獲得,即為登陸表單提交的URL) String surl = "http://login.goodjobs.cn/index.php/action/UserLogin"; /**  * 首先要和URL下的URLConnection對話。 URLConnection可以很容易的從URL得到。比如: // Using  * java.net.URL and //java.net.URLConnection  */ URL url = new URL(surl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); /**  * 然後把串連設為輸出模式。URLConnection通常作為輸入來使用,比如下載一個Web頁。  * 通過把URLConnection設為輸出,你可以把資料向你個Web頁傳送。下面是如何做:  */ connection.setDoOutput(true); /**  * 最後,為了得到OutputStream,簡單起見,把它約束在Writer並且放入POST資訊中,例如: ...  */ OutputStreamWriter out = new OutputStreamWriter(connection  .getOutputStream(), "GBK");        //其中的memberName和password也是閱讀html代碼得知的,即為表單中對應的參數名稱 out.write("memberName=myMemberName&password=myPassword"); // post的關鍵所在! // remember to clean up out.flush(); out.close(); // 取得cookie,相當於記錄了身份,供下次訪問時使用 String cookieVal = connection.getHeaderField("Set-Cookie");

登陸成功後,即可訪問其他URL了。 

 String s = "http://user.goodjobs.cn/dispatcher.php/module/Resume/action/Preview"; //重新開啟一個串連        url = new URL(s); HttpURLConnection resumeConnection = (HttpURLConnection) url  .openConnection(); if (cookieVal != null) {            //發送cookie資訊上去,以表明自己的身份,否則會被認為沒有許可權  resumeConnection.setRequestProperty("Cookie", cookieVal); } resumeConnection.connect(); InputStream urlStream = resumeConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader(  new InputStreamReader(urlStream)); String ss = null; String total = ""; while ((ss = bufferedReader.readLine()) != null) {  total += ss; } IOUtils.write(total, new FileOutputStream("d:/index.html")); bufferedReader.close(); 

通過上述方式,就能訪問帶有許可權控制的URL了。思路即為:類比登陸,取得cookie以記錄身份,下次請求時發送cookie以表明身份。

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.