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

news/2024/5/9 21:44:36/文章来源:https://blog.csdn.net/weixin_34221036/article/details/86431249
原文:使用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");
复制代码

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

 




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

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

相关文章

[网站摘录]TOP小区流程分析

原文地址&#xff1a;http://www.mscbsc.com/bbs/thread-656686-1-1.html#73转载于:https://blog.51cto.com/10237569/1840620

Dapper:The member of type SeoTKD cannot be used as a parameter Value

异常汇总&#xff1a;http://www.cnblogs.com/dunitian/p/4523006.html#dapper 上次说了一下Dapper的扩展Dapper.Contrib http://www.cnblogs.com/dunitian/p/5710382.html 以及这个异常&#xff1a;Dapper.Contrib&#xff1a;GetAsync<T> only supports an entity with…

IIs 网站应用程序与虚拟目录的区别及高级应用说明(文件分布式存储方案)【转】...

对于IIS网站&#xff0c;大伙用的比较多&#xff0c;就不啰嗦了。 今天和说说大伙比较少使用的"IIS应用程序”和虚拟目录的区别及高级应用场景&#xff0c;文件分布式存储方案。 1&#xff1a;IIS网站&#xff1a; 一个网站&#xff0c;基本就是一个站点&#xff0c;绑定N…

你通晓SaaS吗?不自行搭建门户网站的三大理由

就算你创业家们已经对SaaS动了心&#xff0c;也要关注SalientGroup公司发布的新研究结果&#xff1a; 1、SaaS在获得资金。近50%的基于SaaS的初创公司成功地融到了资金――融资成功率之高是其他行业领域无法企及的。 2、基于SaaS的企业在增长。SaaS市场的增长率比软件市场快3倍…

asp.net 网站 发布时 去掉.cs文件

VS2013在WIN8下扁平的UI和我今天锈垢的大脑&#xff0c;让找这个设置找了好半天&#xff01;&#xff01;&#xff01;OK&#xff0c;言归正传。在要发布的网站上右键&#xff0c;选择"发布网站"。在发布窗口中&#xff0c;会让你选择一个发布配置文件&#xff0c;没…

钓鱼网站飙升居然因为这个原因...

2019独角兽企业重金招聘Python工程师标准>>> 2017年注定是个不太平的年份&#xff0c;钓鱼网站的数量已经达到了巅峰状态…… 虽然各大主流浏览器已经推进网站HTTPS的部署&#xff0c;但也正是因为这个原因&#xff0c;一部人认为只要安装了SSL证书就可以保证网站的…

凡客诚品官方网站的前端改进建议

打开http://www.vancl.com/发现采用的Asp.net&#xff0c;这点我感到很欣慰&#xff0c;毕竟国内采用.net技术体系的优秀网站少之又少。好奇之余右键-查看源码&#xff0c;却不由得皱起眉头&#xff0c;在此提几个可以让网站更快的前端建议&#xff1a; 01.合并头部的script为一…

Servlet过滤器实现网站访问计数器功能

实现网站在线访问计数器功能&#xff0c;网站的初始值设置为1000 &#xff08;1&#xff09;创建CountFilter的类&#xff0c;实现javax。servlet.Filter接口&#xff0c;是一个过滤器对象&#xff0c;通过过滤器实现统计网站人数功能&#xff1a; 123456789101112131415161718…

2017年最受欢迎的10个编程挑战网站

2019独角兽企业重金招聘Python工程师标准>>> https://mp.weixin.qq.com/s/nnswkOs_FAq1NHDzfX8mwQ 转载于:https://my.oschina.net/u/3705388/blog/1575013

记一次使用Node.js electron打包网站的记录

具体步骤请参考&#xff1a;http://blog.csdn.net/a727911438/article/details/70834467 打包时出现了不少问题&#xff0c;逐一记录下来以供其他人参考。 package.json文件内容 {"name": "appname","version": "0.1.0","main&qu…

SEO是什么意思?SEO有什么用,怎么做SEO?

什么是SEO&#xff1f;关于SEO的定义&#xff0c;在网络上可以找到很多。如果你去百度一下&#xff1a;SEO是什么。或者你直接去百度百科搜一下&#xff1a;SEO。百度就会向你陈列出关于SEO的定义。它会告诉你&#xff1a; SEO由英文Search Engine Optimization缩写而来&#x…

高性能网站架构之缓存篇—Redis集群搭建

看过 高性能网站架构之缓存篇--Redis安装配置和高性能网站架构之缓存篇--Redis使用配置端口转发 这两篇文章的&#xff0c;相信你已经对redis有一定的了解&#xff0c;并能够安装上&#xff0c;进行简单的使用了&#xff0c;但是在咱们的实际应用中&#xff0c;使用redis肯定不…

内容换行_内容换行或分段不会影响到SEO优化和搜索引擎收录抓取

换行是为了看上去更加美观&#xff0c;而分段表示一个段落的结束&#xff0c;将会使内容版面更加美观&#xff0c;利于人们的阅读。内容是换行还是分段、文字的大小、颜色等不同情况的使用&#xff0c;对于搜索引擎收录抓取都是没有任何影响的&#xff0c;它们的不同使用只会影…

网站改成静态页面打不开_公司网站404,不淡定有啥办法,该有的态度还是要有...

了解网络营销&#xff0c;多元生活伴你左右&#xff0c;欢迎观看正阳说网络营销课程_12今天来聊一聊关于网站404的那些事儿&#xff0c;喜欢上网的朋友多多少少还是会遇到这个问题&#xff0c;为什么会出现这个原因呢&#xff1f;主要是用户操作失误&#xff1b;网站链接书写错…

linux车机系统怎么进工厂模式,工厂方法模式 - 跟JBPM学习设计模式_Linux编程_Linux公社-Linux系统门户网站...

模式简介工厂方法模式&#xff0c;定义一个用于创建对象的接口&#xff0c;让子类决定实例化那个类&#xff0c;其使一个类的实例化延迟到其子类中。前边我们学习了简单工厂模式&#xff0c;简单工厂模式的最大优势在于工厂类中包含了必要逻辑判断&#xff0c;根据客户端的条件…

seo服务器渲染_关于SSR( 服务端渲染 )其利与弊是什么?

服务端渲染&#xff08;SSR&#xff09;原理和客户端&#xff08;CSR&#xff09;渲染区别一、服务端渲染&#xff08;SSR&#xff09;是什么服务端渲染简单来说就是&#xff1a;用户使用的浏览器浏览的都是一些没有复杂逻辑的、简单的页面&#xff0c;这些页面都是在后端将 ht…

个人博客系统服务器,服务器搭建WordPress个人博客网站

WordPress 是世界上使用最广泛的博客系统之一&#xff0c;是一款开源的PHP软件。有丰富的插件模板资源&#xff0c;使用WordPress可以快速搭建独立的博客网站。WordPress-Logo-PNG-Picture.png本教程软件环境基于CentOS 6.8 64位&#xff0c;从配置LNMP环境开始一步步搭建属于你…

简单用户登录网站(HttpServlet1.2版本)

案例说明:当用户尚未登录就访问欢迎界面时,页面跳转到登录界面,并显示提示信息; 若用户填写的信息与固定用户信息不一致时,登录界面显示错误提示信息;否则跳转到欢迎页面,显示用户名信息. 新建Login2.java -- 用户登录界面,当用户信息输入错误时,会显示提醒信息.(当用户直接访问…

linux服务器如何上传网站,Linux服务器如何发布asp.net网站

ASP.NET core是一个用于net程序跨平台的框架&#xff0c;在此基础上会重写windows、Linux&#xff0c;以实现所有net程序、网站的跨平台。该开发框架主要用于构建基于云的现代web应用。.net开发应用运行于windows平台&#xff0c;由于成本原因而大量使用免费Linux平台&#xff…

通过url账号密码登录其他网站_记一次巨水的网站测试

01本人菜鸡&#xff0c;大佬们亲喷~长话短说就是得到了授权测试一下网站&#xff0c;事先说了网站是前后端分离的。整个过程没有啥骚操作&#xff0c;都比较基础。02给了一个url&#xff0c;由于这是公司某业务系统的管理口&#xff0c;只有一个登录界面。如下图。常规测试下登…