HttpWebrequest来模拟登陆的全过程
2011-07-07 13:14
507 查看
根据我上面的几个小积累,其实平时饿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:处理登陆的servletpackage 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>
再次上个运行截图吧:
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:处理登陆的servletpackage 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>
再次上个运行截图吧:
相关文章推荐
- [ 转]c# 使用 HttpWebRequest模拟登陆(附带验证码)
- 用 c# 使用HttpWebRequest模拟登陆(带验证码)
- 使用C#的HttpWebRequest模拟登陆网站
- 转:使用C#的HttpWebRequest模拟登陆网站
- c#第一篇 在WPF的window窗体中使用httpwebrequest实现模拟登陆网页,并在webbroser控件中显示
- C# 利用HttpWebRequest模拟登陆获取数据设置Accept-Encoding为gzip,deflate后返回的网页是乱码处理
- [转发]HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用
- c# 使用 HttpWebRequest模拟登陆(附带验证码)
- 使用 HttpWebRequest模拟登陆(附带验证码)
- C#如何HttpWebRequest模拟登陆,获取服务端返回Cookie以便登录请求后使用
- 使用C#的HttpWebRequest模拟登陆网站
- httpwebrequest模拟登陆 显示乱码
- c# 使用 HttpWebRequest模拟登陆(附带验证码)
- HttpWebRequest模拟登陆,存储Cookie以便登录请求后使用
- 使用C#的HttpWebRequest模拟登陆网站
- 使用C#的HttpWebRequest模拟登陆网站
- c# 使用 HttpWebRequest模拟登陆(附带验证码)
- C# : WebRequest发起Http Post请求模拟登陆并cookie处理示例
- c# 使用 HttpWebRequest模拟登陆(附带验证码)
- 使用HttpWebRequest和HttpWebResponse实现模拟登录需要登陆后才可以访问的页面