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¶ms=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); } }
程序员的基础教程:菜鸟程序员