1>通过HttpWebRequest模拟登陆

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.DirectoryServices.Protocols;
using System.ServiceModel.Security;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Text.RegularExpressions; namespace BaiduCang
{
/// <summary>
/// 有关HTTP请求的辅助类
/// </summary>
public class HttpWebResponseUtility
{
private static readonly string DefaultUserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
/// <summary>
/// 创建GET方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreateGetHttpResponse(string url, int? timeout, string userAgent, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "GET";
request.UserAgent = DefaultUserAgent;
if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
}
return request.GetResponse() as HttpWebResponse;
}
/// <summary>
/// 创建POST方式的HTTP请求
/// </summary>
/// <param name="url">请求的URL</param>
/// <param name="parameters">随同请求POST的参数名称及参数值字典</param>
/// <param name="timeout">请求的超时时间</param>
/// <param name="userAgent">请求的客户端浏览器信息,可以为空</param>
/// <param name="requestEncoding">发送HTTP请求时所用的编码</param>
/// <param name="cookies">随同HTTP请求发送的Cookie信息,如果不需要身份验证可以为空</param>
/// <returns></returns>
public static HttpWebResponse CreatePostHttpResponse(string url, IDictionary<string, string> parameters, int? timeout, string userAgent, Encoding requestEncoding, CookieCollection cookies)
{
if (string.IsNullOrEmpty(url))
{
throw new ArgumentNullException("url");
}
if (requestEncoding == null)
{
throw new ArgumentNullException("requestEncoding");
}
HttpWebRequest request = null;
//如果是发送HTTPS请求
if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request = WebRequest.Create(url) as HttpWebRequest;
request.ProtocolVersion = HttpVersion.Version10;
}
else
{
request = WebRequest.Create(url) as HttpWebRequest;
}
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.AllowAutoRedirect = false; if (!string.IsNullOrEmpty(userAgent))
{
request.UserAgent = userAgent;
}
else
{
request.UserAgent = DefaultUserAgent;
} if (timeout.HasValue)
{
request.Timeout = timeout.Value;
}
if (cookies != null)
{
request.CookieContainer = new CookieContainer();
request.CookieContainer.Add(cookies);
} //如果需要POST数据
if (!(parameters == null || parameters.Count == 0))
{
StringBuilder buffer = new StringBuilder();
int i = 0;
foreach (string key in parameters.Keys)
{
if (i > 0)
{
buffer.AppendFormat("&{0}={1}", key, parameters[key]);
}
else
{
buffer.AppendFormat("{0}={1}", key, parameters[key]);
}
i++;
}
byte[] data = requestEncoding.GetBytes(buffer.ToString());
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
} return request.GetResponse() as HttpWebResponse;
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
} /// <summary>
/// 获取post中input的值
/// </summary>
/// <param name="content">返回的html</param>
/// <returns></returns>
public static Dictionary<string, string> GetPostValuesFromContent(string content)
{
Dictionary<string, string> dics = new Dictionary<string, string>();
StringBuilder sbPattern = new StringBuilder();
sbPattern.Append("<input").Append("[^>]*?").Append("/?>");
Regex regex = new Regex(sbPattern.ToString());
MatchCollection matchList = regex.Matches(content);
foreach (Match match in matchList)
{
string inputValue = match.Groups[0].Value; sbPattern = new StringBuilder();
sbPattern.Append("name=\"").Append("([^\"]*?)").Append("\"");
regex = new Regex(sbPattern.ToString());
string name = regex.Match(inputValue).Groups[1].Value; sbPattern = new StringBuilder();
sbPattern.Append("value=\"").Append("([^\"]*?)").Append("\"");
regex = new Regex(sbPattern.ToString());
string value = regex.Match(inputValue).Groups[1].Value; dics.Add(name, System.Web.HttpContext.Current.Server.UrlEncode(value));
} return dics;
} /// <summary>
/// 获取post中input的值
/// </summary>
/// <param name="content">返回的html</param>
/// <returns></returns>
public static Dictionary<string, string> GetPostValuesFromUrl(string url)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream, Encoding.UTF8);
string content = reader.ReadToEnd();
reader.Close();
responseStream.Close(); return GetPostValuesFromContent(content);
} /// <summary>
/// 从Headers的Cookie中获取到系统的cookie
/// </summary>
/// <param name="setCookie">headers中的cookie字符串</param>
/// <param name="cookieName">系统cookie的name</param>
/// <returns></returns>
public static string GetCookieFromSetCookie(string setCookie, string cookieName)
{
StringBuilder sbPattern = new StringBuilder();
sbPattern.AppendFormat("{0}=", cookieName).Append("(.*?)").Append(";");
Regex regex = new Regex(sbPattern.ToString());
Match match = regex.Match(setCookie);
return match.Groups[1].Value;
} /// <summary>
/// 获取登陆后的跳转页面的html
/// </summary>
/// <param name="cookieName">系统cookie的name</param>
/// <param name="cookieValue">系统cookie的value</param>
/// <param name="redirectUrl">登陆后跳转的url</param>
/// <returns></returns>
public static string GetRedirctUrlHtml(string cookieName, string cookieValue, string redirectUrl, Encoding encoding)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(redirectUrl);
request.Method = "GET";
request.Headers.Add("Cookie", cookieName + "=" + cookieValue); HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader reader = new StreamReader(stream, encoding);
return reader.ReadToEnd();
}
}
}

  

2>模拟登陆demo,直接从项目中挖出来的,实现的模拟登陆客户的oa系统和erp系统的功能,然后审核代办消息,审核的功能未实现。代码实现的是模拟登陆成功后,获取跳转后的页面的html。代码中实际地址和账户非真实数据。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Net;
using BaiduCang;
using System.IO;
using System.Text.RegularExpressions; public partial class Default2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//LoginJsjd();
//LoginOA();
LoginErp();
} public void LoginJsjd()
{
string loginUrl = "http://192.168.0.2/jsjd/login.aspx";
string redirectUrl = "http://192.168.0.2/jsjd/wfi.ashx?act=audit&id=e77ff6a5-4e17-4fb6-b696-82bf5b3c717f&msgid=bc5b6d50-f315-414e-841f-e382ca1a4f8e&comment=&result=Approve";
Encoding encoding = Encoding.GetEncoding("gb2312");
string cookieName = ".ASPXAUTH"; Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("txtName", "8888");
parameters.Add("txtPassword", "8888"); Response.Write(Login(loginUrl, loginUrl, redirectUrl, cookieName, encoding, parameters));
} public void LoginOA()
{
string loginUrl = "http://192.168.0.2:8090/dcwork/j_bsp_security_check/up";
string redirectUrl = "http://192.168.0.2:8090/dcwork/processlist.cmd?method=taskinfoportal";
Encoding encoding = Encoding.GetEncoding("gb2312");
string cookieName = "JSESSIONID"; Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("j_username", "888888");
parameters.Add("j_password", "888888"); Response.Write(Login(loginUrl, loginUrl, redirectUrl, cookieName, encoding, parameters));
} public void LoginErp()
{
string loginUrl = "http://192.168.0.2:8000/OA_HTML/RF.jsp?function_id=26668&resp_id=-1&resp_appl_id=-1&security_group_id=0&lang_code=ZHS&params=KQ0ueFd3h5ncJDQ0.532EQ&oas=NqL6dDNwywXNVCwleKSBLw";
string portUrl = "http://192.168.0.2:8000/OA_HTML/OA.jsp?page=/oracle/apps/fnd/sso/login/webui/MainLoginPG&_ri=0&_ti=128180147&language_code=ZHS&requestUrl=&oapc=18&oas=zlyIwYnA_a_ouuYU0LTLzw..";
string redirectUrl = "http://192.168.0.2:8000/OA_HTML/OA.jsp?OAFunc=OAHOMEPAGE";
Encoding encoding = Encoding.GetEncoding("gb2312");
string cookieName = "JSESSIONID"; Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("usernameField", "888888");
parameters.Add("passwordField", "888888"); Response.Write(Login(loginUrl, portUrl, redirectUrl, cookieName, encoding, parameters));
} /// <summary>
/// 登陆后返回指定页面的html
/// </summary>
/// <param name="loginUrl">登陆页面url</param>
/// <param name="portUrl">登陆提交的post页面url</param>
/// <param name="redirectUrl">登陆成功后跳转的页面url</param>
/// <param name="cookieName">cookie名称</param>
/// <param name="encoding">编码方式</param>
/// <param name="nameAndPassword">用户名和密码对应的文本框的name和值</param>
/// <returns></returns>
public string Login(string loginUrl, string portUrl, string redirectUrl, string cookieName, Encoding encoding, Dictionary<string, string> nameAndPassword)
{
Dictionary<string, string> parameters = HttpWebResponseUtility.GetPostValuesFromUrl(loginUrl); //给参数字典中的用户名和密码赋值
foreach (var item in nameAndPassword)
{
parameters[item.Key] = item.Value;
} foreach (var item in parameters)
{
Response.Write(string.Format("{0}:{1}", item.Key, item.Value));
Response.Write("</br>");
} HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(
portUrl, parameters, null, null, encoding, null); string setCookie = response.Headers["Set-Cookie"];
string cookie = HttpWebResponseUtility.GetCookieFromSetCookie(setCookie, cookieName);
return HttpWebResponseUtility.GetRedirctUrlHtml(cookieName, cookie, redirectUrl, encoding);
}
}

  

程序员的基础教程:菜鸟程序员

通过HttpWebRequest实现模拟登陆的更多相关文章

  1. c# 使用 HttpWebRequest模拟登陆

    c# 使用 HttpWebRequest模拟登陆(附带验证码) 分类: C# .net2010-06-04 00:50 35647人阅读 评论(43) 收藏 举报 c#exceptionstreams ...

  2. c# 使用 HttpWebRequest模拟登陆(附带验证码)

    在C#中,可以使用HttpWebRequest进行相关的模拟登陆,登陆后进行相关的操作,比如抓取数据,页面分析,制作相关登陆助手等等. 先说下流程 1.使用httpwebrequest先进入你要登录的 ...

  3. 使用C#的HttpWebRequest模拟登陆访问人人网

    使用任何语言做模拟登陆或者抓取访问页面,无外乎以下思路: 第一 启用一个web访问会话方法或者实例化一个web访问类,如.net中的HttpWebRequest:第二 模拟POST或者GET方式提交的 ...

  4. 使用C#的HttpWebRequest模拟登陆访问人人网(转)

    无论使用任何语言做模拟登陆或者抓取访问页面,无外乎以下思路:第一 启用一个web访问会话方法或者实例化一个web访问类,如.net中的HttpWebRequest:第二 模拟POST或者GET方式提交 ...

  5. .net+jquery+ashx实现客户端模拟登陆扩展

    客户端实现:login namespace LoginApp { partial class Form1 { /// <summary> /// 必需的设计器变量. /// </su ...

  6. 如何模拟登陆添加了CSRF保护的网站

    上次写了篇文章,内容是如何利用WebClient模拟登陆CSRF控制的网站,回复中有人还是不理解,现在另开一篇,打算说说用Python如何来登陆. 开写之前,先说下为什么webrequest不行,常规 ...

  7. C# 模拟登陆

    原理 我们知道,一般需要登录的网站,服务器和客户端都会有一段时间的会话保持,而这个会话保持是在登录时候建立的, 服务端和客户端都会持有这个KEY,在后续访问时,都需要核对这两个KEY是否一致. 而客户 ...

  8. Python 爬虫模拟登陆知乎

    在之前写过一篇使用python爬虫爬取电影天堂资源的博客,重点是如何解析页面和提高爬虫的效率.由于电影天堂上的资源获取权限是所有人都一样的,所以不需要进行登录验证操作,写完那篇文章后又花了些时间研究了 ...

  9. Python模拟登陆新浪微博

    上篇介绍了新浪微博的登陆过程,这节使用Python编写一个模拟登陆的程序.讲解与程序如下: 1.主函数(WeiboMain.py): import urllib2 import cookielib i ...

随机推荐

  1. Linux运维学习笔记-软硬链接知识总结

    文件链接   硬链接,通过索引节点来进行链接 硬链接原理图 硬链接的创建: 直接执行命令“ln 源文件 硬链接文件”,即可完成创建硬链接. 硬链接知识小结: 1.具有相同Inode节点号的多个文件是互 ...

  2. Idea 使用 Maven 搭建 Web 项目

    传送门: 袁咩咩的小小博客 Maven项目对象模型(POM),可以通过一小段描述信息来管理项目的构建,报告和文档的软件项目管理工具. 使用它来搭建项目可以省去很多操作,它不仅有依赖管理.自动生成项目站 ...

  3. 华为荣耀7i手动更改DNS,提高网页加载速度

    为什么在同样的Wi-Fi网络下,别人的手机可以秒开网页,但自己的手机却总会慢个半拍或是经常打不开,简直龟速.有时还会加载网页失败.我想大部分人都遇到过吧. 今天本人给大家介绍一种方法,可以加快打开网页 ...

  4. python print 控制台输出中文

    在pycharm里面的控制台用print输出信息,  本意想输出中文, 但是实际上是u\xxxx. 可以用这种方式: print("%s " % cn_string)

  5. Spring容器初始化数据(数据库)BeanPostProcessor的应用

    1.目的:在Spring启动的时候加载在数据库保存的配置信息,一方面杜绝随意修改,一方面方便管理 2.BeanPostProcessor是Spring提供的一个方法通过implements方式实现 会 ...

  6. 转转转![Spring MVC] - 500/404错误处理-SimpleMappingExceptionResolver

    参考博客: http://www.cnblogs.com/dongying/p/6129937.html http://www.cnblogs.com/rollenholt/archive/2012/ ...

  7. postman tests实例记录(还没看,一些常用的)

    这段时间准备测试api接口,postman这个工具很是方便,特别是里面的tests的javascript脚本. 记录一下测试接口常用的tests验证的实例. 1.设置环境变量 postman.setE ...

  8. mac下安装wxPython2.8.12.1方法

    搭建robot_framework 环境 找不到 wxPython2.8.12.1的解决方法 1.mac终端pip安装robotframework-ride后 启动ride.py报: wxPython ...

  9. 【POJ】3378 Crazy Thairs(树状数组+dp+高精)

    题目 传送门:QWQ 分析 题意:给个数列,求有多少五元上升组 考虑简化一下问题:如果题目求二元上升组怎么做. 仿照一下逆序对,用树状数组维护一下就ok了. 三元怎么做呢? 把二元的拓展一位就可以了, ...

  10. Jenkins是什么?

    Jenkins 是一个可扩展的持续集成引擎. 主要用于: l 持续.自动地构建/测试软件项目. l 监控一些定时执行的任务. Jenkins拥有的特性包括: l 易于安装-只要把jenkins.war ...