通过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

相关文章

SpringBoot3实现Gzip压缩优化的技术指南

《SpringBoot3实现Gzip压缩优化的技术指南》随着Web应用的用户量和数据量增加,网络带宽和页面加载速度逐渐成为瓶颈,为了减少数据传输量,提高用户体验,我们可以使用Gzip压缩HTTP响应,... 目录1、简述2、配置2.1 添加依赖2.2 配置 Gzip 压缩3、服务端应用4、前端应用4.1 N

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

Python FastAPI+Celery+RabbitMQ实现分布式图片水印处理系统

《PythonFastAPI+Celery+RabbitMQ实现分布式图片水印处理系统》这篇文章主要为大家详细介绍了PythonFastAPI如何结合Celery以及RabbitMQ实现简单的分布式... 实现思路FastAPI 服务器Celery 任务队列RabbitMQ 作为消息代理定时任务处理完整

Java枚举类实现Key-Value映射的多种实现方式

《Java枚举类实现Key-Value映射的多种实现方式》在Java开发中,枚举(Enum)是一种特殊的类,本文将详细介绍Java枚举类实现key-value映射的多种方式,有需要的小伙伴可以根据需要... 目录前言一、基础实现方式1.1 为枚举添加属性和构造方法二、http://www.cppcns.co

使用Python实现快速搭建本地HTTP服务器

《使用Python实现快速搭建本地HTTP服务器》:本文主要介绍如何使用Python快速搭建本地HTTP服务器,轻松实现一键HTTP文件共享,同时结合二维码技术,让访问更简单,感兴趣的小伙伴可以了... 目录1. 概述2. 快速搭建 HTTP 文件共享服务2.1 核心思路2.2 代码实现2.3 代码解读3.

MySQL双主搭建+keepalived高可用的实现

《MySQL双主搭建+keepalived高可用的实现》本文主要介绍了MySQL双主搭建+keepalived高可用的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,... 目录一、测试环境准备二、主从搭建1.创建复制用户2.创建复制关系3.开启复制,确认复制是否成功4.同

Java实现文件图片的预览和下载功能

《Java实现文件图片的预览和下载功能》这篇文章主要为大家详细介绍了如何使用Java实现文件图片的预览和下载功能,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... Java实现文件(图片)的预览和下载 @ApiOperation("访问文件") @GetMapping("

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

JSON Web Token在登陆中的使用过程

《JSONWebToken在登陆中的使用过程》:本文主要介绍JSONWebToken在登陆中的使用过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录JWT 介绍微服务架构中的 JWT 使用结合微服务网关的 JWT 验证1. 用户登录,生成 JWT2. 自定义过滤

Java实现时间与字符串互相转换详解

《Java实现时间与字符串互相转换详解》这篇文章主要为大家详细介绍了Java中实现时间与字符串互相转换的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、日期格式化为字符串(一)使用预定义格式(二)自定义格式二、字符串解析为日期(一)解析ISO格式字符串(二)解析自定义