C# HttpWebRequest GET HTTP HTTPS 請求

這個需求來自于我最近練手的一個項目,在項目中我需要將一些自己發表的和收藏整理的網文集中到一個地方存放,如果全部采用手工操作工作量大而且繁瑣,因此周公決定利用C#來實現。在很多地方都需要驗證用戶身份才可以進行下一步操作,這就免不了POST請求來登錄,在實際過程中發現有些網站登錄是HTTPS形式的,在解決過程中遇到了一些小問題,現在跟大家分享。
通用輔助類
下面是我編寫的一個輔助類,在這個類中采用了HttpWebRequest中發送GET/HTTP/HTTPS請求,因為有的時候需要獲取認證信息(如Cookie),所以返回的是HttpWebResponse對象,有了返回的HttpWebResponse實例,可以獲取登錄過程中返回的會話信息,也可以獲取響應流。
代碼如下:

復制代碼
復制代碼
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"; 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; //總是接受  } } } 
復制代碼
復制代碼

?

從上面的代碼中可以看出POST數據到HTTP和HTTPS站點不同,POST數據到HTTPS站點的時候需要設置ServicePointManager類的ServerCertificateValidationCallback屬性,并且在POST到https://passport.baidu.com/?login時還需要將HttpWebResquest實例的ProtocolVersion屬性設置為HttpVersion.Version10(這個未驗證是否所有的HTTPS站點都需要設置),否則在調用GetResponse()方法時會拋出“基礎連接已經關閉: 連接被意外關閉。”的異常。

用法舉例
這個類用起來也很簡單:
(1)POST數據到HTTPS站點,用它來登錄百度:

復制代碼
復制代碼
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.Headers["Set-Cookie"];中獲取并設置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內容的方法(包括服務器使用壓縮方式傳輸的數據),但限于篇幅和其它方面的原因,此處省略掉了。如有機會,在以后的文章中會繼續講述這方面的內容。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/387552.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/387552.shtml
英文地址,請注明出處:http://en.pswp.cn/news/387552.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HttpStatusCode

https://docs.microsoft.com/en-us/dotnet/api/system.net.httpstatuscode?viewnetframework-4.7.2 422 UnprocessableEntity What HTTP status response code should I use if the request is missing a required parameter? Status 422 seems most appropiate based on the…

numpy 和tensorflow 中的乘法

矩陣乘法&#xff1a;tf.matmul() np.dot() &#xff0c; 逐元素乘法&#xff1a;tf.multiply() np.multiply()轉載于:https://www.cnblogs.com/lizhiqing/p/10307760.html

啟用了不安全的HTTP方法

安全風險&#xff1a;可能會在Web 服務器上上載、修改或刪除Web 頁面、腳本和文件。可能原因&#xff1a;Web 服務器或應用程序服務器是以不安全的方式配置的。修訂建議&#xff1a;如果服務器不需要支持WebDAV&#xff0c;請務必禁用它&#xff0c;或禁止不必要的HTTP 方法。方…

Mysql學習總結(4)——MySql基礎知識、存儲引擎與常用數據類型

2019獨角獸企業重金招聘Python工程師標準>>> 1、基礎知識 1.1、數據庫概述 簡單地說&#xff1a;數據庫&#xff08;Database或DB&#xff09;是存儲、管理數據的容器&#xff1b;嚴格地說&#xff1a;數據庫是“按照某種數據結構對數據進行組織、存儲和管理的容器”…

django權限二(多級菜單的設計以及展示)

多級權限菜單設計級標題欄 我們現在只有數據展示,要進入其他url還需要手動的輸入路徑,非常的麻煩,所以我們要設計 一個導航欄以及側邊多級菜單欄,這個展示是通過stark組件的設計的增刪改查頁面,而 每一個 頁面我們都需要有導航欄和側邊的權限菜單欄,所以把這個公共的部分提起到…

6.17 dokcer(一)Compose 簡介

Compose 簡介 Compose 項目是 Docker 官方的開源項目&#xff0c;負責實現對 Docker 容器集群的快速編排。從功能上看&#xff0c;跟 OpenStack 中的 Heat 十分類似。 其代碼目前在 https://github.com/docker/compose 上開源。 Compose 定位是 「定義和運行多個 Docker 容器的…

【系統架構理論】一篇文章精通:Spring Cloud Netflix Eureka

是官方文檔的總結 http://spring.io/projects/spring-cloud-netflix#overview 講解基于2.0.2版本官方文檔 https://cloud.spring.io/spring-cloud-static/spring-cloud-netflix/2.0.2.RELEASE/single/spring-cloud-netflix.html Netflix提供了以下功能&#xff1a; 服務發現&am…

Flink DataStream 編程入門

流處理是 Flink 的核心&#xff0c;流處理的數據集用 DataStream 表示。數據流從可以從各種各樣的數據源中創建&#xff08;消息隊列、Socket 和 文件等&#xff09;&#xff0c;經過 DataStream 的各種 transform 操作&#xff0c;最終輸出文件或者標準輸出。這個過程跟之前文…

騰訊手游如何提早揭露游戲外掛風險?

目前騰訊SR手游安全測試限期開放免費專家預約&#xff01;點擊鏈接&#xff1a;手游安全測試立即預約&#xff01; 作者&#xff1a;sheldon&#xff0c;騰訊高級安全工程師 商業轉載請聯系騰訊WeTest獲得授權&#xff0c;非商業轉載請注明出處。 文中動圖無法顯示&#xff0c…

基于ARM Cortex-M0+ 的Bootloader 參考

源&#xff1a; 基于ARM Cortex-M0內核的bootloader程序升級原理及代碼解析轉載于:https://www.cnblogs.com/LittleTiger/p/10312784.html

小猿圈web前端之網站性能優化方案

現在前端不僅要能做出一個網站頁面&#xff0c;還要把這個頁面做的炫酷&#xff0c;那需要很大程度的優化&#xff0c;那么怎么優化才更好呢&#xff1f;小猿圈總結了一下自己優化的方案&#xff0c;感興趣的朋友可以看一下。一般網站優化都是優化后臺&#xff0c;如接口的響應…

下面介紹一個開源的OCR引擎Tesseract2。值得慶幸的是雖然是開源的但是它的識別率較高,并不比其他引擎差勁。網上介紹Tessnet2也是當時時間排名第三的識別引擎,只是后來慢慢不維護了,目前是G

下面介紹一個開源的OCR引擎Tesseract2。值得慶幸的是雖然是開源的但是它的識別率較高&#xff0c;并不比其他引擎差勁。網上介紹Tessnet2也是當時時間排名第三的識別引擎&#xff0c;只是后來慢慢不維護了&#xff0c;目前是Google在維護&#xff0c;大家都知道Google 在搞電子…

js 更改json的 key

let t data.map(item > {return{fee: item[費用],companyName1: item.companyName,remark1: item.remark,beginTime1: item.beginTime,endTime1: item.endTime}})console.log(t) 源地址&#xff1a;https://www.cnblogs.com/Marydon20170307/p/8676611.html轉載于:https:/…

1.4版本上線(第八次會議)

在小組成員連夜趕工的奮斗下&#xff0c;終于在昨天深夜成功實現了UI界面功能 至此&#xff0c;我們的系統終于真正可實用而不是局限在命令行進行互動了 由于python嵌入數據庫功能實現難度較大&#xff0c;迫于時間的局限性&#xff0c;我們選擇了用json文件與txt文件進行替代&…

分UV教程

第一步 首先&#xff0c;打開一個練習場景“空中預警機1.max”&#xff08;這事小弟平時的練習做的不好獻丑了&#xff09;。&#xff08;圖01&#xff09; 圖01 第二步 這里我們拿機翼來舉例子&#xff0c;隱藏除機翼意外的其他模型。&#xff08;圖02&#xff09; 圖02 第三步…

k8s系列--- dashboard認證及分級授權

http://blog.itpub.net/28916011/viewspace-2215214/ 因版本不一樣&#xff0c;略有改動 Dashboard官方地址&#xff1a; https://github.com/kubernetes/dashboard dashbord是作為一個pod來運行&#xff0c;需要serviceaccount賬號來登錄。 先給dashboad創建一個專用的認證信息…

JAVA項目開發

16年java軟件開發經驗&#xff0c;全職項目開發&#xff0c;項目可簽合同、開普票和專票。 主要承接項目&#xff1a; 1、網站開發項目 自主開發千帆CMS動態發布系統&#xff0c;基于java/springboot2/jpa/easyui開發&#xff0c;簡單易用&#xff0c;后臺與前端分離&#xff0…

3dmax基本操作

1、基本操作平移視圖&#xff08;你所說的移動&#xff09;&#xff1a;CTRLP&#xff0c;或者用&#xff0c;滾輪。按住鼠標滾輪不放拖動&#xff0c;就行了。旋轉&#xff1a; ALT滾輪。按住ALT鍵不放&#xff0c;利用滾輪的移動&#xff08;滾輪也要按著不放&#xff09…

padding影響整個div的實際寬度

padding影響整個div的實際寬度 1.不讓padding影響整個div的實際寬度 所以要設置css屬性&#xff1a; box-sizing:box-sizingposted on 2019-01-25 16:58 玉貔貅 閱讀(...) 評論(...) 編輯 收藏 轉載于:https://www.cnblogs.com/yupixiu/p/10320564.html

unity3d 任務頭上的血條

人物的名稱與血條的繪制方法很簡單&#xff0c;但是我們需要解決的問題是如何在3D世界中尋找合適的坐標。因為3D世界中的人物是會移動的&#xff0c;它是在3D世界中移動&#xff0c;并不是在2D平面中移動&#xff0c;但是我們需要將3D的人物坐標換算成2D平面中的坐標&#xff0…