这篇文章是有关模拟登录网站方面的。

实现步骤;

  1. 启用一个web会话
  2. 发送模拟数据请求(POST或者GET)
  3. 获取会话的CooKie 并根据该CooKie继续访问登录后的页面,获取后续访问的页面数据。

我们以登录人人网为例,首先需要分析人人网登录时POST的数据格式,这个可以通过IE9中只带的F12快捷键,调出开发人员工具。如下图:

通过开始捕获得到POST的地址和POST的数据

POST数据:

email=aaa@163.com&password=111&icode=&origURL=http%3A%2F%2Fwww.renren.com%2Fhome&domain=renren.com&key_id=1&_rtk=90484476

POST地址:

http://www.renren.com/PLogin.do

下面就是代码示例来得到登录后页面(http://guide.renren.com/guide)的数据

HTMLHelper类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Threading; namespace Test
{
public class HTMLHelper
{
/// <summary>
/// 获取CooKie
/// </summary>
/// <param name="loginUrl"></param>
/// <param name="postdata"></param>
/// <param name="header"></param>
/// <returns></returns>
public static CookieContainer GetCooKie(string loginUrl, string postdata, HttpHeader header)
{
HttpWebRequest request = null;
HttpWebResponse response = null;
try
{
CookieContainer cc = new CookieContainer();
request = (HttpWebRequest)WebRequest.Create(loginUrl);
request.Method = header.method;
request.ContentType = header.contentType;
byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata);
request.ContentLength = postdatabyte.Length;
request.AllowAutoRedirect = false;
request.CookieContainer = cc;
request.KeepAlive = true; //提交请求
Stream stream;
stream = request.GetRequestStream();
stream.Write(postdatabyte, 0, postdatabyte.Length);
stream.Close(); //接收响应
response = (HttpWebResponse)request.GetResponse();
response.Cookies = request.CookieContainer.GetCookies(request.RequestUri); CookieCollection cook = response.Cookies;
//Cookie字符串格式
string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri); return cc;
}
catch (Exception ex)
{ throw ex;
}
} /// <summary>
/// 获取html
/// </summary>
/// <param name="getUrl"></param>
/// <param name="cookieContainer"></param>
/// <param name="header"></param>
/// <returns></returns>
public static string GetHtml(string getUrl, CookieContainer cookieContainer,HttpHeader header)
{
Thread.Sleep(1000);
HttpWebRequest httpWebRequest = null;
HttpWebResponse httpWebResponse = null;
try
{
httpWebRequest = (HttpWebRequest)HttpWebRequest.Create(getUrl);
httpWebRequest.CookieContainer = cookieContainer;
httpWebRequest.ContentType = header.contentType;
httpWebRequest.ServicePoint.ConnectionLimit = header.maxTry;
httpWebRequest.Referer = getUrl;
httpWebRequest.Accept = header.accept;
httpWebRequest.UserAgent = header.userAgent;
httpWebRequest.Method = "GET";
httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();
Stream responseStream = httpWebResponse.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string html = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
httpWebRequest.Abort();
httpWebResponse.Close();
return html;
}
catch (Exception e)
{
if (httpWebRequest != null) httpWebRequest.Abort();
if (httpWebResponse != null) httpWebResponse.Close();
return string.Empty;
}
}
} public class HttpHeader
{
public string contentType { get; set; } public string accept { get; set; } public string userAgent { get; set; } public string method{get;set;} public int maxTry { get; set; }
}
}

测试用例:

  HttpHeader header = new HttpHeader();
header.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
header.contentType = "application/x-www-form-urlencoded";
header.method = "POST";
header.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
header.maxTry = 300; string html = HTMLHelper.GetHtml("http://guide.renren.com/guide", HTMLHelper.GetCooKie("http://www.renren.com/PLogin.do",
"email=aaa@163.com&password=111&icode=&origURL=http%3A%2F%2Fwww.renren.com%2Fhome&domain=renren.com&key_id=1&_rtk=90484476", header), header); Console.WriteLine(html); Console.ReadLine();

通过程序登录了网站后而直接进入登录后的页面。

首先还是发起一个启用一个web会话,然后发送模拟数据请求,获取会话的CooKie,再根据该CooKie将其写入到本地,通过程序直接打开登录后的页面。

该功能可用于无法修改第三方系统源代码而要做系统单点登录。

我们先在HTMLHelper类中添加一个方法:

 1 /// <summary>
2 /// 获取CookieCollection
3 /// </summary>
4 /// <param name="loginUrl"></param>
5 /// <param name="postdata"></param>
6 /// <param name="header"></param>
7 /// <returns></returns>
8 public static CookieCollection GetCookieCollection(string loginUrl, string postdata, HttpHeader header)
9 {
10 HttpWebRequest request = null;
11 HttpWebResponse response = null;
12 try
13 {
14 CookieContainer cc = new CookieContainer();
15 request = (HttpWebRequest)WebRequest.Create(loginUrl);
16 request.Method = header.method;
17 request.ContentType = header.contentType;
18 byte[] postdatabyte = Encoding.UTF8.GetBytes(postdata);
19 request.ContentLength = postdatabyte.Length;
20 request.AllowAutoRedirect = false;
21 request.CookieContainer = cc;
22 request.KeepAlive = true;
23
24 //提交请求
25 Stream stream;
26 stream = request.GetRequestStream();
27 stream.Write(postdatabyte, 0, postdatabyte.Length);
28 stream.Close();
29
30 //接收响应
31 response = (HttpWebResponse)request.GetResponse();
32 response.Cookies = request.CookieContainer.GetCookies(request.RequestUri);
33
34 CookieCollection cook = response.Cookies;
35 //Cookie字符串格式
36 string strcrook = request.CookieContainer.GetCookieHeader(request.RequestUri);
37
38 return cook;
39 }
40 catch (Exception ex)
41 {
42
43 throw ex;
44 }
45 }

再根据获取的CookieCollection写入本地,并打开登录后的页面

 1   [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
2
3 public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);
4
5
6 HttpHeader header = new HttpHeader();
7 header.accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/x-silverlight, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-ms-application, application/x-ms-xbap, application/vnd.ms-xpsdocument, application/xaml+xml, application/x-silverlight-2-b1, */*";
8 header.contentType = "application/x-www-form-urlencoded";
9 header.method = "POST";
10 header.userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";
11 header.maxTry = 300;
12
13
14 CookieCollection mycookie = HTMLHelper.GetCookieCollection("http://www.renren.com/PLogin.do",
15 "email=aaa%40163.com&password=111&icode=&origURL=http%3A%2F%2Fwww.renren.com%2Fhome&domain=renren.com&key_id=1&_rtk=90484476", header);
16
17
18 foreach (Cookie cookie in mycookie) //将cookie设置为浏览的cookie
19 {
20
21 InternetSetCookie(
22
23 "http://" + cookie.Domain.ToString(),
24
25 cookie.Name.ToString(),
26
27 cookie.Value.ToString() + ";expires=Sun,22-Feb-2099 00:00:00 GMT");
28
29 }
30 System.Diagnostics.Process.Start("http://guide.renren.com/guide");

这样即可直接通过程序打开登录后的页面:

以上为转发的原文,原文地址:http://blog.csdn.net/htsnoopy/article/details/7094224

可以看到原文下面的评论有好多问到那个postdata从哪里弄到的,这个可以在IE浏览器的F12下看请求正文,但我的理解是还要看网站的登录是采用什么方式传递的,有的就在这里看不到内容,比如原文实验用的人人网站,现在看来在请求正文中就看不到任何内容,还好我工作中遇到的这个项目在请求正文中里恰好能找到原文作者贴出的那个字符串

转:使用C#的HttpWebRequest模拟登陆网站的更多相关文章

  1. 使用C#的HttpWebRequest模拟登陆网站

    很久没有写新的东西了,今天在工作中遇到的一个问题,感觉很有用,有种想记下来的冲动. 这篇文章是有关模拟登录网站方面的. 实现步骤: 启用一个web会话 发送模拟数据请求(POST或者GET) 获取会话 ...

  2. c# 使用 HttpWebRequest模拟登陆

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

  3. 【教程】手把手教你如何利用工具(IE9的F12)去分析模拟登陆网站(百度首页)的内部逻辑过程

    [前提] 想要实现使用某种语言,比如Python,C#等,去实现模拟登陆网站的话,首先要做的事情就是使用某种工具,去分析本身使用浏览器去登陆网页的时候,其内部的执行过程,内部逻辑. 此登陆的逻辑过程, ...

  4. HttpWebRequest模拟c#网站登录

     用户名 密码 模拟登录asp.net开发的网站 关心两个问题:通过控件属性获取数据.响应事件. 上面是一个普通的asp.net表单.输入用户名.密码后,点击按钮将会进入各自绑定的后台函数,而不仅仅是 ...

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

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

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

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

  7. 【小白学爬虫连载(10)】–如何用Python实现模拟登陆网站

    Python如何实现模拟登陆爬取Python实现模拟登陆的方式简单来说有三种:一.采用post请求提交表单的方式实现.二.利用浏览器登陆网站记录登陆成功后的cookies,采用get的请求方式,传入c ...

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

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

  9. python requests 模拟登陆网站,抓取数据

    抓取页面数据的时候,有时候我们需要登陆才可以获取页面资源,那么我们需要登陆以后才可以跳转到对应的资源页面,那么我们需要通过模拟登陆,登陆成功以后再次去抓取对应的数据. 首先我们需要通过手动方式来登陆一 ...

随机推荐

  1. 负载均衡 > 常见问题

    证书管理相关问题 常用证书申请流程 1.本地生成私钥:openssl genrsa -out privateKey.pem 2048 其中privateKey.pem为您的私钥文件,请妥善保管. 2. ...

  2. SATA1.0,2.0,3.0区别

    外观没区别,接口都一样,线也一样,就是传输速率不一样,控制芯片不一样SATA1.0理论传输速度为1.5Gbit/s SATA2.0理论传输速度为3Gbit/sSATA2.0理论传输速度为6Gbit/s ...

  3. hdu5772-String problem(最大权闭合子图问题)

    解析: 多校标答 第一类:Pij 表示第i个点和第j个点组合的点,那么Pij的权值等于w[i][j]+w[j][i](表示得分)第二类:原串中的n个点每个点拆出一个点,第i个点权值为 –a[s[i]] ...

  4. hadoop深入研究:(十六)——Avro序列化与反序列化

    转载请写明来源地址:http://blog.csdn.net/lastsweetop/article/details/9773233 所有源码在github上,https://github.com/l ...

  5. 2016"百度之星" - 资格赛(Astar Round1) 1001

    思路:第一个做法就是:每读入起始位置i和结束位置j,就从这位置i到位置j计算,可是TLE了,后面我想想要是我输入一个最长的字符串,且以最大次数计算开始位置1到结束位置100000,那么这计算量是很大的 ...

  6. mysql基本介绍

    RDBMS:1.数据库创建.删除除2.创建表.删除表.修改表3.索引的创建.删除4.用户和权限5.数据增.删.改6.查询 DML:Data Manapulate Language: 数据操作语言   ...

  7. 用Less循环生成样式

    需求是这样的,我要给一个轮播图设置不同的背景图,由于每张图片的背景图路劲都不一样,所以需要对每个单独的元素自定义图片路径.然后想到Less语法有mixin机制,就这样实现了一个递归function,然 ...

  8. [Spring入门学习笔记][静态资源]

    遗留问题 在上一节课的作业中,我们一定遇到了一点问题——虽然将页面内容正确的返回给了浏览器,但是浏览器显示的样式却是不正确的,这是因为在HTML的\标签中我们这样引入了CSS资源: <link ...

  9. python-布尔值

    布尔只有两个值:0,1 1或0 真或假 下面的值在作为布尔表达式的时候,会被解释器看作假(false) False    None    0   ""    ()    []   ...

  10. EffectiveC#01--避免返回内部类对象的引用

    此篇是对00中第3点的再一次阐述. 1.如果一个属性返回一个引用类型,那么调用者就可以访问这个对象的公共成员,也包括修改这些属性的状态. public class MyBusinessObject { ...