申公前幾日和一個(gè)客戶做系統(tǒng)對(duì)接,以前和客戶對(duì)接一般采用webservice或者json 解析的方式,直接調(diào)用標(biāo)準(zhǔn)解析就可以。沒想到客戶用“請(qǐng)求響應(yīng)模式”,直接訪問人家的接口地址取數(shù)據(jù),無奈打造一個(gè)通用的訪問類吧
站在用戶的角度思考問題,與客戶深入溝通,找到金安網(wǎng)站設(shè)計(jì)與金安網(wǎng)站推廣的解決方案,憑借多年的經(jīng)驗(yàn),讓設(shè)計(jì)與互聯(lián)網(wǎng)技術(shù)結(jié)合,創(chuàng)造個(gè)性化、用戶體驗(yàn)好的作品,建站類型包括:網(wǎng)站設(shè)計(jì)制作、網(wǎng)站建設(shè)、企業(yè)官網(wǎng)、英文網(wǎng)站、手機(jī)端網(wǎng)站、網(wǎng)站推廣、空間域名、虛擬空間、企業(yè)郵箱。業(yè)務(wù)覆蓋金安地區(qū)。
參考MSDN的解釋:
HttpWebRequest類:提供WebRequest類的Http特定的實(shí)現(xiàn)。
HttpWebRequest 類對(duì) WebRequest 中定義的屬性和方法提供支持,也對(duì)使用戶能夠直接與使用 HTTP 的服務(wù)器交互的附加屬性和方法提供支持。
不要使用構(gòu)造函數(shù)創(chuàng)建HttpWebRequest實(shí)例,請(qǐng)使用System.Net.WebRequest.Create(URI uriString)來創(chuàng)建實(shí)例,如果URI是Http://或Https://,
返回的是HttpWebRequest對(duì)象。(建立請(qǐng)求特定URI的對(duì)象)
當(dāng)向資源發(fā)送數(shù)據(jù)時(shí),GetRequestStream方法返回用于發(fā)送數(shù)據(jù)的Stream對(duì)象。(獲取請(qǐng)求數(shù)據(jù)的流對(duì)象)
GetResponse方法向RequestUri屬性指定的資源發(fā)出同步請(qǐng)求并返回包含該響應(yīng)的HttpWebResponse。(獲取來自internet的響應(yīng))
好了,直接上代碼:
using System.Net; using System.IO; using System.Security.Cryptography.X509Certificates; using System.Net.Security; using System.Windows.Forms; /* * 作者:申公 * 日期: * 說明:此類提供http,POST和GET訪問遠(yuǎn)程接口 * */ namespace ZJS.EDI.Business.HttpUtility { ///調(diào)用實(shí)例:/// 有關(guān)HTTP請(qǐng)求的輔助類 /// 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;//字符集 ////// 創(chuàng)建GET方式的HTTP請(qǐng)求 /// /// 請(qǐng)求的URL /// 請(qǐng)求的超時(shí)時(shí)間 /// 請(qǐng)求的客戶端瀏覽器信息,可以為空 /// 隨同HTTP請(qǐng)求發(fā)送的Cookie信息,如果不需要身份驗(yàn)證可以為空 ///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; } /// /// 創(chuàng)建POST方式的HTTP請(qǐng)求 /// /// 請(qǐng)求的URL /// 隨同請(qǐng)求POST的參數(shù)名稱及參數(shù)值字典 /// 隨同HTTP請(qǐng)求發(fā)送的Cookie信息,如果不需要身份驗(yàn)證可以為空 ///public static HttpWebResponse CreatePostHttpResponse(string url, string parameters, CookieCollection cookies) { if (string.IsNullOrEmpty(url)) { throw new ArgumentNullException("url"); } HttpWebRequest request = null; Stream stream = null;//用于傳參數(shù)的流 try { //如果是發(fā)送HTTPS請(qǐng)求 if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase)) { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); request = WebRequest.Create(url) as HttpWebRequest; //創(chuàng)建證書文件 System.Security.Cryptography.X509Certificates.X509Certificate objx509 = new System.Security.Cryptography.X509Certificates.X509Certificate(Application.StartupPath + @"\\licensefile\zjs.cer"); //添加到請(qǐng)求里 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";//協(xié)議 request.UserAgent = DefaultUserAgent;//請(qǐng)求的客戶端瀏覽器信息,默認(rèn)IE request.Timeout = 6000;//超時(shí)時(shí)間,寫死6秒 //隨同HTTP請(qǐng)求發(fā)送的Cookie信息,如果不需要身份驗(yàn)證可以為空 if (cookies != null) { request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(cookies); } //如果需求POST傳數(shù)據(jù),轉(zhuǎn)換成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; } //驗(yàn)證服務(wù)器證書回調(diào)自動(dòng)驗(yàn)證 private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) { return true; //總是接受 } /// /// 獲取數(shù)據(jù) /// /// 響應(yīng)對(duì)象 ///public static string OpenReadWithHttps(HttpWebResponse HttpWebResponse) { Stream responseStream = null; StreamReader sReader = null; String value = null; try { // 獲取響應(yīng)流 responseStream = HttpWebResponse.GetResponseStream(); // 對(duì)接響應(yīng)流(以"utf-8"字符集) sReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")); // 開始讀取數(shù)據(jù) value = sReader.ReadToEnd(); } catch (Exception) { //日志異常 } finally { //強(qiáng)制關(guān)閉 if (sReader != null) { sReader.Close(); } if (responseStream != null) { responseStream.Close(); } if (HttpWebResponse != null) { HttpWebResponse.Close(); } } return value; } /// /// 入口方法:獲取傳回來的XML文件 /// /// 請(qǐng)求的URL /// 隨同請(qǐng)求POST的參數(shù)名稱及參數(shù)值字典 /// 隨同HTTP請(qǐng)求發(fā)送的Cookie信息,如果不需要身份驗(yàn)證可以為空 ///public static string GetResultXML(string url, string parameters, CookieCollection cookies) { return OpenReadWithHttps(CreatePostHttpResponse(url, parameters, cookies)); } } }
/// 調(diào)用主程序 /// public class Program { static string strUrlPre = ; // 測(cè)試環(huán)境Url static string strKey = ;// 簽名密鑰 static string strMethod = ;// 方法編號(hào) static void Main(string[] args) { //MessageBox.Show("請(qǐng)注意,馬上將進(jìn)行保存操作!"); StringBuilder sbRequestData =;//請(qǐng)求參數(shù) // 發(fā)送請(qǐng)求 StringBuilder sbUrl = new StringBuilder(); // 請(qǐng)求URL內(nèi)容 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); } }