您好,登錄后才能下訂單哦!
申公前幾日和一個客戶做系統對接,以前和客戶對接一般采用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); } }
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。