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. Server JRE 简介

    Server JRE, 服务器版JRE JRE安装包, JDK安装包, 以及 Server JRE 压缩包, 在 Java SE Download 页面都可以下载: http://www.oracle ...

  2. test20181020 B君的第一题

    题意 分析 二次剩余问题. x,y相当于二次方程 \[ x^2-bx+c=0 \mod{p} \] 的两根. 摸意义下的二次方程仍然考虑判别式\(\Delta=b^2-4c\). 它能开根的条件是\( ...

  3. Trie树学习1

    Trie树.也称为字典数,前缀树,每一个单词的每一个字母依照顺序相应一个节点.有重合的前缀就共享节点. 理想情况下(满的情况).假若全部的单词都是N长,则树共同拥有N层,每层都是26个子节点. 在程序 ...

  4. DNS记录类型名单

    原文:http://www.worldlingo.com/ma/enwiki/zh_cn/List_of_DNS_record_types DNS记录类型名单 这 DNS记录类型名单 提供一个方便索引 ...

  5. mac下搭建appium记录

    要安装的东西: jdk(要配置环境) , sdk(要配置环境) ,node(要配置环境), python(要配置环境) ,appium(要配置环境),appium-python-client ,xco ...

  6. HDU 3746 Cyclic Nacklace (用kmp求循环节)

    Cyclic Nacklace Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)T ...

  7. Bootstrap-Other:HTML编码规范

    ylbtech-Bootstrap-Other:HTML编码规范 1.返回顶部 1. Bootstrap HTML编码规范 语法 用两个空格来代替制表符(tab) -- 这是唯一能保证在所有环境下获得 ...

  8. [Android] 开发第八天

    View 类是所有 UI组件的基类,它包含的 XML 属性和方法是所有组件都可使用的. ViewGroup 继承了 View 类,主要当作容器类使用,它是一个抽象类,实际使用中会使用它的子类作为容器. ...

  9. 搜索引擎Lucene之皮毛

    一.Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,但它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索 ...

  10. blktrace btt结果分析

    对于btt的结果分析十分的困难,我和同事花了很多的时间在网上查找btt输出的每一项参数的意义,试图更好的分析bio的统计信息,但网上文章一大抄,翻来覆去就是那几篇文章. 本文中内容参考了以下网址: 1 ...