通过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);
     }
}

  

猜你喜欢

转载自blog.csdn.net/snowfoxmonitor/article/details/80518395
今日推荐