在使用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以表明身份。
轉自:http://blog.csdn.net/prince2270/article/details/6137810
