C#中WebRequest請求的一些心得
阿新 • • 發佈:2018-12-10
在C#開發中經常需要進行Web遠端訪問,方法很多,也使用了很久,但一直沒有做一個總結。
C#中用來進行遠端請求的方法有很多,如WebClient,WebRequest等,也各有特點。今天在這裡主要介紹WebRequest。
先從相對入門的不需要證書驗證,不需要登入的開始。
1 //Get 2 public string GetContent(string uri, Encoding coding) 3 { 4 //Get請求中請求引數等直接拼接在url中 5 WebRequest request = WebRequest.Create(uri);6 7 //返回對Internet請求的響應 8 WebResponse resp = request.GetResponse(); 9 10 //從網路資源中返回資料流 11 Stream stream = resp.GetResponseStream(); 12 13 StreamReader sr = new StreamReader(stream, coding); 14 15 //將資料流轉換文字串 16 stringresult = sr.ReadToEnd(); 17 18 //關閉流資料 19 stream.Close(); 20 sr.Close(); 21 22 return result; 23 }
上面的方法是GET型別的請求。下面介紹POST請求。
1 //POST 2 public string GetContentPost(string uri, string data, Encoding coding) 3 { 4 WebRequest request = WebRequest.Create(uri);5 request.ContentType = "application/x-www-form-urlencoded"; 6 request.Method = "POST"; 7 8 //將字串資料轉化為位元組串,這也是POST請求與GET請求區別的地方 9 byte[] buffer = coding.GetBytes(data); 10 11 //用於將資料寫入Internet資源 12 Stream stream = request.GetRequestStream(); 13 stream.Write(buffer, 0, buffer.Length); 14 request.ContentLength = buffer.Length; 15 16 WebResponse response = request.GetResponse(); 17 18 //從網路資源中返回資料流 19 stream = response.GetResponseStream(); 20 21 StreamReader sr = new StreamReader(stream, coding); 22 23 //將資料流轉換文字串 24 string result = sr.ReadToEnd(); 25 26 //關閉流資料 27 stream.Close(); 28 sr.Close(); 29 30 return result; 31 }
上面兩個方法的特點就是簡單易使用,用於獲取HTML文件。缺點就是無法處理那些需要證書的頁面。
下面我們介紹需要證書驗證的頁面如何請求。
1 //回撥驗證證書問題 2 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 3 { 4 //直接返回true,接受指定證書進行身份驗證 5 return true; 6 } 7 8 //Get 9 public string GetContent(string uri, Encoding coding) 10 { 11 12 //下面一行程式碼一定解除安裝請求開始前。 13 //使用回撥的方法進行驗證。 14 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); 15 16 //Get請求中請求引數等直接拼接在url中 17 WebRequest request = WebRequest.Create(uri); 18 19 //返回對Internet請求的響應 20 WebResponse resp = request.GetResponse(); 21 22 //從網路資源中返回資料流 23 Stream stream = resp.GetResponseStream(); 24 25 StreamReader sr = new StreamReader(stream, coding); 26 27 //將資料流轉換文字串 28 string result = sr.ReadToEnd(); 29 30 //關閉流資料 31 stream.Close(); 32 sr.Close(); 33 34 return result; 35 } 36 37 //POST 38 public string GetContentPost(string uri, string data, Encoding coding) 39 { 40 //下面一行程式碼一定解除安裝請求開始前。 41 //使用回撥的方法進行驗證。 42 ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult); 43 44 WebRequest request = WebRequest.Create(uri); 45 request.ContentType = "application/x-www-form-urlencoded"; 46 request.Method = "POST"; 47 48 //將字串資料轉化為位元組串,這也是POST請求與GET請求區別的地方 49 byte[] buffer = coding.GetBytes(data); 50 51 //用於將資料寫入Internet資源 52 Stream stream = request.GetRequestStream(); 53 stream.Write(buffer, 0, buffer.Length); 54 request.ContentLength = buffer.Length; 55 56 WebResponse response = request.GetResponse(); 57 58 //從網路資源中返回資料流 59 stream = response.GetResponseStream(); 60 61 StreamReader sr = new StreamReader(stream, coding); 62 63 //將資料流轉換文字串 64 string result = sr.ReadToEnd(); 65 66 //關閉流資料 67 stream.Close(); 68 sr.Close(); 69 70 return result; 71 }
我們以百度舉例,看訪問百度時如何獲取百度伺服器的證書相關資訊。
只需在證書驗證的回撥函式中新增幾行程式碼即可。
1 //回撥驗證證書問題 2 public bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 3 { 4 Console.WriteLine("證書的有效日期:" + certificate.GetEffectiveDateString()); 5 Console.WriteLine("證書的到期日期:" + certificate.GetExpirationDateString()); 6 Console.WriteLine("證書格式名稱:" + certificate.GetFormat()); 7 Console.WriteLine("證書辦法機構名稱:" + certificate.Issuer); 8 Console.WriteLine("金鑰演算法資訊:" + certificate.GetKeyAlgorithm()); 9 Console.WriteLine("證書的公鑰:" + certificate.GetPublicKeyString()); 10 Console.WriteLine("證書序列號:" + certificate.GetSerialNumberString()); 11 // 總是接受 12 return true; 13 }
使用如下GET方式訪問百度。即可得到截圖效果。
GetContent("https://www.baidu.com/", Encoding.UTF8); Console.WriteLine(str);
然後通過瀏覽器導航欄的鎖標識,即可直接檢視百度的相關證書資訊。
通過對比可以知道,獲取到的證書完全正確。所以如果想對訪問的網站有證書檢測,也可以通過這種方式。避免出現請求被攔截等問題。