通过HttpWebRequest实现模拟登陆

2024-01-15 15:18

本文主要是介绍通过HttpWebRequest实现模拟登陆,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

1>通过HttpWebRequest模拟登陆

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
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。代码中实际地址和账户非真实数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
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实现模拟登陆的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/609326

相关文章

hdu1043(八数码问题,广搜 + hash(实现状态压缩) )

利用康拓展开将一个排列映射成一个自然数,然后就变成了普通的广搜题。 #include<iostream>#include<algorithm>#include<string>#include<stack>#include<queue>#include<map>#include<stdio.h>#include<stdlib.h>#include<ctype.h>#inclu

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

【Prometheus】PromQL向量匹配实现不同标签的向量数据进行运算

✨✨ 欢迎大家来到景天科技苑✨✨ 🎈🎈 养成好习惯,先赞后看哦~🎈🎈 🏆 作者简介:景天科技苑 🏆《头衔》:大厂架构师,华为云开发者社区专家博主,阿里云开发者社区专家博主,CSDN全栈领域优质创作者,掘金优秀博主,51CTO博客专家等。 🏆《博客》:Python全栈,前后端开发,小程序开发,人工智能,js逆向,App逆向,网络系统安全,数据分析,Django,fastapi

让树莓派智能语音助手实现定时提醒功能

最初的时候是想直接在rasa 的chatbot上实现,因为rasa本身是带有remindschedule模块的。不过经过一番折腾后,忽然发现,chatbot上实现的定时,语音助手不一定会有响应。因为,我目前语音助手的代码设置了长时间无应答会结束对话,这样一来,chatbot定时提醒的触发就不会被语音助手获悉。那怎么让语音助手也具有定时提醒功能呢? 我最后选择的方法是用threading.Time

Android实现任意版本设置默认的锁屏壁纸和桌面壁纸(两张壁纸可不一致)

客户有些需求需要设置默认壁纸和锁屏壁纸  在默认情况下 这两个壁纸是相同的  如果需要默认的锁屏壁纸和桌面壁纸不一样 需要额外修改 Android13实现 替换默认桌面壁纸: 将图片文件替换frameworks/base/core/res/res/drawable-nodpi/default_wallpaper.*  (注意不能是bmp格式) 替换默认锁屏壁纸: 将图片资源放入vendo

usaco 1.2 Transformations(模拟)

我的做法就是一个一个情况枚举出来 注意计算公式: ( 变换后的矩阵记为C) 顺时针旋转90°:C[i] [j]=A[n-j-1] [i] (旋转180°和270° 可以多转几个九十度来推) 对称:C[i] [n-j-1]=A[i] [j] 代码有点长 。。。 /*ID: who jayLANG: C++TASK: transform*/#include<

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略

Kubernetes PodSecurityPolicy:PSP能实现的5种主要安全策略 1. 特权模式限制2. 宿主机资源隔离3. 用户和组管理4. 权限提升控制5. SELinux配置 💖The Begin💖点点关注,收藏不迷路💖 Kubernetes的PodSecurityPolicy(PSP)是一个关键的安全特性,它在Pod创建之前实施安全策略,确保P

工厂ERP管理系统实现源码(JAVA)

工厂进销存管理系统是一个集采购管理、仓库管理、生产管理和销售管理于一体的综合解决方案。该系统旨在帮助企业优化流程、提高效率、降低成本,并实时掌握各环节的运营状况。 在采购管理方面,系统能够处理采购订单、供应商管理和采购入库等流程,确保采购过程的透明和高效。仓库管理方面,实现库存的精准管理,包括入库、出库、盘点等操作,确保库存数据的准确性和实时性。 生产管理模块则涵盖了生产计划制定、物料需求计划、

C++——stack、queue的实现及deque的介绍

目录 1.stack与queue的实现 1.1stack的实现  1.2 queue的实现 2.重温vector、list、stack、queue的介绍 2.1 STL标准库中stack和queue的底层结构  3.deque的简单介绍 3.1为什么选择deque作为stack和queue的底层默认容器  3.2 STL中对stack与queue的模拟实现 ①stack模拟实现