在使用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以表明身份。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。