Java模擬登入WEB系統的簡單示例
阿新 • • 發佈:2019-01-06
package cwebs; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; /* * 模擬登入系統的簡單示例 * */ public class LoginSample { static String sURL="http://localhost:8080/LoginSample/"; static String responseCookie;//標示Session必須 //測試登入功能,返回“自動”登入後的頁面 public static String login(String usr,String pwd) throws IOException { StringBuilder sbR = new StringBuilder(); //訪問URL,並把資訊存入sb中 //如果服務端登入成功後,服務端的程式碼呼叫下面的程式碼 //response.sendRedirect("welcome.jsp"); //則會不成功,原因(Step2,沒有上傳jsessionid值,導致沒session)如下 //Step1[login.jsp登入成功]->轉到-> //Step2[welcome.jsp不能得到session,判斷沒有登入成功]->轉到->Step3[login.jsp要求使用者登入] URL url = new URL(sURL); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); connection.setDoOutput(true);//允許連線提交資訊 connection.setRequestMethod("POST");//網頁預設“GET”提交方式 StringBuffer sb = new StringBuffer(); sb.append("Name="+usr); sb.append("&Password="+pwd); connection.setRequestProperty("Content-Length", String.valueOf(sb.toString().length())); OutputStream os = connection.getOutputStream(); os.write(sb.toString().getBytes()); os.close(); //取Cookie BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); responseCookie = connection.getHeaderField("Set-Cookie");//取到所用的Cookie System.out.println("cookie:" + responseCookie); //取返回的頁面 String line = br.readLine(); while (line != null) { sbR.append(line); line = br.readLine(); } return sbR.toString(); } //返回頁面 public static String viewPage() throws IOException { StringBuilder sbR = new StringBuilder(); //開啟URL連線 URL url1 = new URL(sURL); HttpURLConnection connection1 = (HttpURLConnection) url1.openConnection(); //給伺服器送登入後的cookie connection1.setRequestProperty("Cookie", responseCookie); //讀取返回的頁面資訊到br1 BufferedReader br1 = new BufferedReader(new InputStreamReader(connection1.getInputStream())); //取返回的頁面,br1轉sbR String line1= br1.readLine(); while (line1 != null) { sbR.append(line1); line1 = br1.readLine(); } return sbR.toString(); } }