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

news/2024/5/13 18:05:53/文章来源:https://blog.csdn.net/weixin_30470857/article/details/99614284
使用C#的HttpWebRequest模拟登陆网站
原文:使用C#的HttpWebRequest模拟登陆网站

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

实现步骤;

  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");
复制代码

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

 




posted on 2016-05-05 11:46 NET未来之路 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/lonelyxmas/p/5461277.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.luyixian.cn/news_show_724426.aspx

如若内容造成侵权/违法违规/事实不符,请联系dt猫网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

SEO站长必备的十大常用搜索引擎高级指令

作为一个seo人员&#xff0c;不懂得必要的搜索引擎高级指令&#xff0c;不是一个合格的seo。网站优化技术配合一些搜索引擎高级指令将使得优化工作变得简单。今日就和大家聊聊SEO站长必备的十大常用搜索引擎高级指令的那些事儿。 【1】引号的用法 把关键字打上引号后把引号部分…

转:游戏玩家集体出逃 社交网站遭遇迷途

原文地址&#xff1a;http://games.sina.com.cn/y/2010-04-27/1130394729.shtml 在经历了摘菜和抢车位等游戏引发的狂热之后&#xff0c; 国内社交游戏玩家集体出逃&#xff0c;社交网站危机显现。 在商业价值和盈利模式的质疑声中&#xff0c;这些依靠游戏起家的Facebook模…

使用phpmyadmin管理远程sql_网站搬家记录-使用cPanel面板从SugarHosts迁出

自从购买了独立服务器&#xff0c;就准备把分散在各处主机的站点迁移到一块。目前最麻烦的就是在SugarHosts.com上的产品公园站点&#xff0c;只能使用cPanel面板&#xff0c;而我对这个面板又不熟悉&#xff0c;故在此做下记录。cPanel是什么cPanel是一套基于Web的自动化hosti…

部分网站为什么上不去_大量网站索引暴跌,百度搞鬼可以如何应对

做SEO的同事一大早跟我说他们站长群一早就炸了&#xff01;只因为进入11月以来&#xff0c;不少的站点收录变慢、收录变少&#xff0c;今天更是有不少站长反馈说&#xff0c;索引量直接砍半。根据提供的索引截图来看&#xff0c;昨天的索引量都出现了断崖式暴跌&#xff0c;200…

《SEO的艺术(原书第2版)》——3.12 规划和评估的高级方法

3.12 规划和评估的高级方法 业务规划有许多方法。其中一种著名的方法是SWOT&#xff08;Strengths、Weaknesses、Opportunities、Threats&#xff0c;优势、劣势、机遇、威胁&#xff09;分析。还有一些方法能够确保规划目标的正确&#xff0c;如SMART&#xff08;Specific、Me…

快速构建LAMP网站平台

快速构建LAMP网站平台1.1 问题 本例要求基于Linux主机快速构建LAMP动态网站平台&#xff0c;并确保可以支撑PHP应用及数据库&#xff0c;完成下列任务&#xff1a; 1&#xff09;安装LAMP平台各组件&#xff0c;启动LAMP平台 软件包&#xff1a;httpd、mariadb-server、mariadb…

[转载]网站性能优化之CSS无图片技术 —— 网站性能优化

一、无图片技术定义在不使用CSS Image&#xff08;通过CSS的引入的背景图片,不包括img标签内的图片&#xff09;情况下生成类似图片效果的技术&#xff1b;换句话的意思就是在使用纯CSS生成类似图片效果的技术。二、为什么要“无图片”&#xff1f;首先我们通过yslow的statisti…

WebRAY网站检查技术支撑平台的实践

平台与网站越来越多&#xff0c;问题更多 互联网服务平台及门户网站已经成为互联网时代政府机关企事业单位的形象代言&#xff0c;是政企单位展示自身形象的一个重要渠道。从国务院办公厅组织开展的第一次全国政府网站普查情况获悉&#xff0c;截至2015年11月&#xff0c;各地区…

强大的跨平台绘制流程图软件网站ProcessOn

一个强大的作图网址&#xff08;https://www.processon.com&#xff09;&#xff0c;告别vision,rose等需要本地安装的软件&#xff0c;只需要连接网络不需要安装任何软件就能制作流程图了。能绘制基本流程图形&#xff0c;flowchart流程图&#xff0c;bpmn,evc企业价值链&…

Google Developers 中国网站正式发布

Google Developers 中国网站 (developers.google.cn) 正式发布&#xff01;Google Developers 中国网站是特别为中国开发者而建立的&#xff0c;它汇集了 Google 为全球开发者所提供的开发技术资源&#xff0c;包括 API 文档、开发案例、技术培训的视频。并涵盖了以下关键开发技…

给自己的网站加入智能聊天功能

引言现在突然发现有很多 QQ 群都开启了群机器人的功能&#xff0c;其中有两个角色&#xff0c;他们分别是&#xff1a;Baby Q 和 QQ 小冰。在 Q 群中&#xff0c;你可以对他们进行任意程度的调戏&#xff0c;不过&#xff0c;遗憾的是鱼和熊掌不可得兼&#xff0c;一个群只能进…

网站已死 互联网永生

从诞生到现在&#xff0c;网站已经走过了20个年头。相比当年的流行&#xff0c;如今它已经开始衰落&#xff0c;逐渐让位于更简单且时髦的智能应用。这些应用更关注的不是搜索效果&#xff0c;而是信息获取。克莱斯安德森(Chris Anderson)向我们解释了这些新应用所反映的资本聚…

j2ee 简单网站搭建:(五)使用 jcaptcha 生成验证码图片

为什么80%的码农都做不了架构师&#xff1f;>>> 《j2ee 简单网站搭建&#xff1a;&#xff08;一&#xff09; windows 操作系统下使用 eclipse 建立 maven web 项目》《j2ee 简单网站搭建&#xff1a;&#xff08;二&#xff09;添加和配置 spring spring-mvc 的…

步步为营-90-SEO(url重写+超链接技巧)

目的:便于搜索引擎抓取 url重写:将带参数的url如:https://i.cnblogs.com/EditPosts.aspx?opt1.修改为https://i.cnblogs.com/EditPosts.aspx_1 1:在BookList修改如下链接方式 href"<%#Eval("Id","/Goods/BookDetail_{0}.aspx") %>"> 2…

asp.net网站接入QQ登录

这两天在做网站第三方登录&#xff0c;总结一下QQ登录吧&#xff0c;支付宝就不用了&#xff08;下载dome把ID什么的换一换就基本可以了。&#xff09;&#xff0c;本文主要说的是代码的实现方式&#xff0c;逻辑部分主要还是根据帮助文档来的。不懂的同学可以先看看文档。 直接…

ios和安卓测试包发布网站http://fir.im的注册与常用功能

作为专业的ios和安卓测试包发布网站&#xff0c;注册超简单。支持输入网址直接下载和二维码扫描下载。功能类似TestFlight ,但又比它强大&#xff0c;支持游客访问密码&#xff0c;ios和安卓测试app都支持。模仿TestFlight &#xff0c;又高于TestFlight 。 1 注册是我见到的最…

兰亭集势(Lightinthebox)网站结构综合分析

于&#xff1a; 2010年 十一月 18日 by admin 兰亭集势 &#xff08;Lightinthebox &#xff09;是中国整合了供应链服务的在线B2C&#xff08;内部叫做L2C,LightInTheBox 2 Customer&#xff09;&#xff0c;该公司拥有一系列的供应商&#xff0c;并拥有自己的数据仓库和长期…

VC2005从开发MFC ActiveX ocx控件到发布到.net网站的全部过程

开篇语&#xff1a;最近在弄ocx控件发布到asp.net网站上使用&#xff0c;就是用户在使用过程中&#xff0c;自动下载安装ocx控件。&#xff08;此文章也是总结了网上好多人写的文章&#xff0c;我只是汇总一下&#xff0c;加上部分自己的东西&#xff0c;在这里感谢所有在网上发…

事件mouseover ,mouseout ,mouseenter,mouseleave的区别

鼠标滑过的时候出现一个层&#xff0c;当鼠标滑到当前层的话mouseover和mouseout在低版本的浏览器会出现闪动的现象&#xff0c;解决这个现象的办法有许多&#xff0c;不过我觉得有一种是最简单的那就是把mouseover和mouseout换成对应的mouseenter和mouseleave。mouseover ,mou…

[C++]3-1 得分(Score ACM-ICPC Seoul 2005,UVa1585)

Question 习题3-1 得分(Score ACM-ICPC Seoul 2005,UVa1585) 题目&#xff1a;给出一个由O和X组成的串&#xff08;长度为1~80&#xff09;&#xff0c;统计得分。 每个O的分数为目前连续出现的O的个数&#xff0c;X的得分为0。 例如&#xff1a;OOXXOXXOOO的得分为1200100123。…