HttpURLConnection模擬用戶登陸


這個話題網上搜一下一大把,大致的方法如下:

URL url = new URL("網頁");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);// 允許連接提交信息
connection.setRequestMethod("POST");// 網頁提交方式“GET”、“POST”
String content = "username=admin&password=admin";
connection.setRequestProperty("Cookie", responseCookie);// 有網站需要將當前的session id一並上傳
OutputStream os = connection.getOutputStream();
os.write(content.toString().getBytes("GBK"));
os.close();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String responseCookie = connection.getHeaderField("Set-Cookie");// 取到所用的Cookie
String sessionIdString = "";
if (responseCookie != null) {
    sessionIdString = responseCookie.substring(0, responseCookie.indexOf(";"));
}
// 輸出內容
String line = br.readLine();
while (line != null) {
    System.out.println(line);
    line = br.readLine();
}
// access
URL url1 = new URL("網頁的登錄后的頁面");
HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();
connection1.setRequestProperty("Cookie", responseCookie);// 給服務器送登錄后的cookie
BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));
String line1 = br1.readLine();
while (line1 != null) {
    // TODO:操作
}

 

有的朋友如果試了,不能在登陸以后訪問其他網頁,可以嘗試在模擬登陸的時候連當前的Session ID一並發給服務器,試試。不過如果網站用了網頁的Token機制,也就是說每個頁面都會產生一個唯一鍵值,而且再加上登錄的驗證碼的過程,那么上面的程序就會遇到相關困難了。

另外,HttpClient應該處理類似功能起來會容易些。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM