這個話題網上搜一下一大把,大致的方法如下:
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");// 取到所用的CookieString sessionIdString = "";if (responseCookie != null) {sessionIdString = responseCookie.substring(0, responseCookie.indexOf(";"));}// 輸出內容String line = br.readLine();while (line != null) {System.out.println(line);line = br.readLine();}// accessURL url1 = new URL("網頁的登錄后的頁面");HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection();connection1.setRequestProperty("Cookie", responseCookie);// 給服務器送登錄后的cookieBufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream()));String line1 = br1.readLine();while (line1 != null) {// TODO:操作}
有的朋友如果試了,不能在登陸以后訪問其他網頁,可以嘗試在模擬登陸的時候連當前的Session ID一並發給服務器,試試。不過如果網站用了網頁的Token機制,也就是說每個頁面都會產生一個唯一鍵值,而且再加上登錄的驗證碼的過程,那么上面的程序就會遇到相關困難了。
另外,HttpClient應該處理類似功能起來會容易些。
