HttpWebRequest和HttpWebResponse
阿新 • • 發佈:2019-02-13
申公前幾日和一個客戶做系統對接,以前和客戶對接一般採用webservice或者json 解析的方式,直接呼叫標準解析就可以。沒想到客戶用“請求響應模式”,直接訪問人家的介面地址取資料,無奈打造一個通用的訪問類吧
參考MSDN的解釋:
HttpWebRequest類:提供WebRequest類的Http特定的實現。
HttpWebRequest 類對 WebRequest 中定義的屬性和方法提供支援,也對使使用者能夠直接與使用 HTTP 的伺服器互動的附加屬性和方法提供支援。
不要使用建構函式建立HttpWebRequest例項,請使用System.Net.WebRequest.Create(URI uriString)來建立例項,如果URI是Http://或Https://,
返回的是HttpWebRequest物件。(建立請求特定URI的物件)
當向資源傳送資料時,GetRequestStream方法返回用於傳送資料的Stream物件。(獲取請求資料的流物件)
GetResponse方法向RequestUri屬性指定的資源發出同步請求並返回包含該響應的HttpWebResponse。(獲取來自internet的響應)
好了,直接上程式碼:
呼叫例項:using System.Net; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Windows.Forms; /* * 作者:申公 * 日期: * 說明:此類提供http,POST和GET訪問遠端介面 * */ namespace ZJS.EDI.Business.HttpUtility { /// <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)";//瀏覽器 private static Encoding requestEncoding = System.Text.Encoding.UTF8;//字符集 /// <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="cookies">隨同HTTP請求傳送的Cookie資訊,如果不需要身份驗證可以為空</param> /// <returns></returns> public static HttpWebResponse CreatePostHttpResponse(string url, string parameters, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = null; Stream stream = null;//用於傳引數的流 try { //如果是傳送HTTPS請求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; //建立證書檔案 System.Security.Cryptography.X509Certificates.X509Certificate objx509 = new System.Security.Cryptography.X509Certificates.X509Certificate(Application.StartupPath + @"\\licensefile\zjs.cer"); //新增到請求裡 request.ClientCertificates.Add(objx509); request.ProtocolVersion = HttpVersion.Version10; } else { request = WebRequest.Create(url) as HttpWebRequest; } request.Method = "POST";//傳輸方式 request.ContentType = "application/x-www-form-urlencoded";//協議 request.UserAgent = DefaultUserAgent;//請求的客戶端瀏覽器資訊,預設IE request.Timeout = 6000;//超時時間,寫死6秒 //隨同HTTP請求傳送的Cookie資訊,如果不需要身份驗證可以為空 if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需求POST傳資料,轉換成utf-8編碼 byte[] data = requestEncoding.GetBytes(parameters); request.ContentLength = data.Length; stream = request.GetRequestStream(); stream.Write(data, 0, data.Length); stream.Close(); } catch (Exception ee) { //寫日誌 //LogHelper. } finally { if (stream != null) { stream.Close(); } } return request.GetResponse() as HttpWebResponse; } //驗證伺服器證書回撥自動驗證 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //總是接受 } /// <summary> /// 獲取資料 /// </summary> /// <param name="HttpWebResponse">響應物件</param> /// <returns></returns> public static string OpenReadWithHttps(HttpWebResponse HttpWebResponse) { Stream responseStream = null; StreamReader sReader = null; String value = null; try { // 獲取響應流 responseStream = HttpWebResponse.GetResponseStream(); // 對接響應流(以"utf-8"字符集) sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取資料 value = sReader.ReadToEnd(); } catch (Exception) { //日誌異常 } finally { //強制關閉 if (sReader != null) { sReader.Close(); } if (responseStream != null) { responseStream.Close(); } if (HttpWebResponse != null) { HttpWebResponse.Close(); } } return value; } /// <summary> /// 入口方法:獲取傳回來的XML檔案 /// </summary> /// <param name="url">請求的URL</param> /// <param name="parameters">隨同請求POST的引數名稱及引數值字典</param> /// <param name="cookies">隨同HTTP請求傳送的Cookie資訊,如果不需要身份驗證可以為空</param> /// <returns></returns> public static string GetResultXML(string url, string parameters, CookieCollection cookies) { return OpenReadWithHttps(CreatePostHttpResponse(url, parameters, cookies)); } } }
/// 呼叫主程式 /// </summary> public class Program { static string strUrlPre = ; // 測試環境Url static string strKey = ;// 簽名金鑰 static string strMethod = ;// 方法編號 static void Main(string[] args) { //MessageBox.Show("請注意,馬上將進行儲存操作!"); StringBuilder sbRequestData =;//請求引數 // 傳送請求 StringBuilder sbUrl = new StringBuilder(); // 請求URL內容 sbUrl.Append(strUrlPre); sbUrl.Append("?"); sbUrl.Append("sign=" + strKeyMD5); sbUrl.Append("&" + sbSystemArgs.ToString()); String strUrl = sbUrl.ToString(); //解析xml檔案 string resultXML = HttpWebResponseUtility.GetResultXML(sbUrl.ToString(), sbRequestData.ToString(), null); } }