HttpWebrequest來模擬登陸的全過程

NO IMAGE

根據我上面的幾個小積累,其實平時餓get和post已經沒問題了,有個特殊的post就是登陸。大家知道登陸問題在server端是session的問題,在客戶端來post的時候其實還是cookie的問題,如何把cookie傳送到server,並且server認為你是登陸成功了呢。這裡給個例子,其實就是CookieContainer的使用,這個使用只需要附帶進去就好了。也就是第一次請求的時候附帶個空的給request,再次request的時候還是把這個給設定到request中去即可,第一次request帶個空的去後,伺服器端就把cookie的資訊寫到了這個container中了,你再次帶這個container去request的話,伺服器如果還是會從這個container裡面找cookie或者再次放入點cookie的。整個程式碼如下,先發c#的模擬。再次發server端的驗證程式碼:

 

 

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Collections.Specialized; 
namespace post_test
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Begin...");
Console.WriteLine("開啟登陸頁面...");
// 設定cookie的container
CookieContainer cookieContainer = new CookieContainer();
// 設定一些公用的請求頭
NameValueCollection collection = new NameValueCollection();
collection.Add("accept-language", "zh-cn,zh;q=0.5");
collection.Add("accept-encoding", "gzip,deflate");
collection.Add("accept-charset", "GB2312,utf-8;q=0.7,*;q=0.7");
collection.Add("cache-control", "max-age=0");
collection.Add("keep-alive", "115");
// 先請求登陸頁面
HttpWebRequest requestLoginPage = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test2/index.jsp");
requestLoginPage.Accept = "text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8";
requestLoginPage.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
requestLoginPage.Headers.Add(collection);
HttpWebResponse responseLoginPage = (HttpWebResponse)requestLoginPage.GetResponse();
Console.WriteLine("開啟登陸頁面狀態:{0}", responseLoginPage.StatusCode);
// 來Post資料到登陸頁面
HttpWebRequest requestLoginToPage = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test2/servlet/LoginServlet");
requestLoginToPage.Accept = "text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8";
requestLoginToPage.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
requestLoginToPage.ContentType = "application/x-www-form-urlencoded";
requestLoginToPage.Method = "POST";
requestLoginToPage.Headers.Add(collection);
requestLoginToPage.CookieContainer = cookieContainer;
String data = "userName=admin&password=123456";
byte[] bytes = Encoding.ASCII.GetBytes(data);
requestLoginToPage.ContentLength = bytes.Length;
Stream streamLoginToPage = requestLoginToPage.GetRequestStream();
streamLoginToPage.Write(bytes, 0, bytes.Length);
streamLoginToPage.Flush();
streamLoginToPage.Close();
HttpWebResponse responseLoginToPage = (HttpWebResponse)requestLoginToPage.GetResponse();
Console.WriteLine("Post資料結果狀態:{0}", responseLoginToPage.StatusCode);
// 開啟登陸狀態頁面
HttpWebRequest requestResultPage = (HttpWebRequest)WebRequest.Create("http://localhost:8080/test2/result.jsp");
requestResultPage.Accept = "text/html,application/xhtml xml,application/xml;q=0.9,*/*;q=0.8";
requestResultPage.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13";
requestResultPage.Headers.Add(collection);
requestResultPage.CookieContainer = cookieContainer;
HttpWebResponse responseResultPage = (HttpWebResponse)requestResultPage.GetResponse();
Console.WriteLine("開啟狀態頁面狀態:{0},內容:{1}", responseLoginPage.StatusCode, new StreamReader(responseResultPage.GetResponseStream(), Encoding.UTF8).ReadToEnd());
Console.Read();
}
}
}

伺服器端也就是3個檔案,一個是登陸頁面,一個是登陸處理的servlet一個是驗證登陸是否成功的jsp。分別如下:

1:登陸頁面

<%@ page language="java"  pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() "://" request.getServerName() ":" request.getServerPort() path "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="<%=request.getContextPath()%>/servlet/LoginServlet" method="post">
<table>
<tr>
<td>使用者名稱</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>密碼</td>
<td><input type="text" name="password" /></td>
</tr>
<tr colspan="2">
<td><input type="submit" value="提交" /></td>
</tr>
</table>
</form>
</body>
</html>

2:處理登陸的servlet

package com.baseframework.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
* 
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
* 
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName = request.getParameter("userName");
String password = request.getParameter("password");
if(userName != null && password != null && userName.equals("admin") && password.equals("123456")) {
request.getSession().setAttribute("login", "true");
// 新增一個session來驗證cookie的效果
request.getSession().setAttribute("count", "123456");
out.println("登陸成功!");
System.out.println("登陸成功!");
} else {
request.getSession().setAttribute("login", "false");
out.println("登陸失敗!");
System.out.println("登陸失敗!");
}
out.flush();
out.close();
}
}

3:判斷登陸結果的頁面

<%@ page language="java" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() "://" request.getServerName() ":" request.getServerPort() path "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'result.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">    
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%
if(session.getAttribute("login") != null && session.getAttribute("login").equals("true")) {
out.println("登陸成功!");
// 列印測試session
out.println("[測試Session的count:"   session.getAttribute("count")   "]");
} else {
out.println("失敗!");
}	
%>
</body>
</html>

 

再次上個執行截圖吧: