這個需求來自於我最近練手的一個項目,在項目中我須要將一些本身發表的和收藏整理的網文集中到一個地方存放,若是所有采用手工操做工做量大並且繁瑣,所以周公決定利用C#來實現。在不少地方都須要驗證用戶身份才能夠進行下一步操做,這就免不了POST請求來登陸,在實際過程當中發現有些網站登陸是HTTPS形式的,在解決過程當中遇到了一些小問題,如今跟你們分享。
通用輔助類
下面是我編寫的一個輔助類,在這個類中採用了HttpWebRequest中發送GET/HTTP/HTTPS請求,由於有的時候須要獲取認證信息(如Cookie),因此返回的是HttpWebResponse對象,有了返回的HttpWebResponse實例,能夠獲取登陸過程當中返回的會話信息,也能夠獲取響應流。
代碼以下:
php
- 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
- {
-
-
-
- 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)";
-
-
-
-
-
-
-
-
- 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;
- }
-
-
-
-
-
-
-
-
-
-
- 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;
-
- 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";
-
- 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);
- }
-
- 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;
- }
- }
- }
從上面的代碼中能夠看出POST數據到HTTP和HTTPS站點不一樣,POST數據到HTTPS站點的時候須要設置ServicePointManager類的ServerCertificateValidationCallback屬性,而且在POST到https://passport.baidu.com/?login時還須要將HttpWebResquest實例的ProtocolVersion屬性設置爲HttpVersion.Version10(這個未驗證是否全部的HTTPS站點都須要設置),不然在調用GetResponse()方法時會拋出「基礎鏈接已經關閉: 鏈接被意外關閉。」的異常。
用法舉例
這個類用起來也很簡單:
(1)POST數據到HTTPS站點,用它來登陸百度:
ajax
- string loginUrl = "https://passport.baidu.com/?login";
- string userName = "userName";
- string password = "password";
- string tagUrl = "http://cang.baidu.com/"+userName+"/tags";
- Encoding encoding = Encoding.GetEncoding("gb2312");
-
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- parameters.Add("tpl", "fa");
- parameters.Add("tpl_reg", "fa");
- parameters.Add("u", tagUrl);
- parameters.Add("psp_tt", "0");
- parameters.Add("username", userName);
- parameters.Add("password", password);
- parameters.Add("mem_pass", "1");
- HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, parameters, null, null, encoding, null);
- string cookieString = response.Headers["Set-Cookie"];
(2)發送GET請求到HTTP站點
在cookieString中包含了服務器端返回的會話信息數據,從中提取了以後能夠設置Cookie下次登陸時帶上這個Cookie就能夠以認證用戶的信息,假設咱們已經登陸成功而且獲取了Cookie,那麼發送GET請求的代碼以下:
瀏覽器
- string userName = "userName";
- string tagUrl = "http://cang.baidu.com/"+userName+"/tags";
- CookieCollection cookies = new CookieCollection();
- response = HttpWebResponseUtility.CreateGetHttpResponse(tagUrl, null, null, cookies);
(3)發送POST請求到HTTP站點
以登陸51CTO爲例:
服務器
- string loginUrl = "http://home.51cto.com/index.php?s=/Index/doLogin";
- string userName = "userName";
- string password = "password";
-
- IDictionary<string, string> parameters = new Dictionary<string, string>();
- parameters.Add("email", userName);
- parameters.Add("passwd", password);
-
- HttpWebResponse response = HttpWebResponseUtility.CreatePostHttpResponse(loginUrl, parameters, null, null, Encoding.UTF8, null);
在這裏說句題外話,CSDN的登陸處理是由http://passport.csdn.net/ajax/accounthandler.ashx這個Handler來處理的。
總結
在本文只是講解了在C#中發送請求到HTTP和HTTPS的用法,分GET/POST兩種方式,爲減小一些繁瑣和機械的編碼,周公將其封裝爲一個類,發送數據以後返回HttpWebResponse對象實例,利用這個實例咱們能夠獲取服務器端返回的Cookie以便用認證用戶的身份繼續發送請求,或者讀取服務器端響應的內容,不過在讀取響應內容時要注意響應格式和編碼,原本在這個類中還有讀取HTML和WML內容的方法(包括服務器使用壓縮方式傳輸的數據),但限於篇幅和其它方面的緣由,此處省略掉了。若有機會,在之後的文章中會繼續講述這方面的內容。
cookie