#region 發送xml檔案給指定網址 /// <summary> /// 發送xml檔案給指定網址 /// </summary> /// <param name="v_strURL">目標Url</param> /// <param name="v_objXMLDoc">需要發送的資料(XmlDocument格式的)</param> /// <returns>伺服器響應</returns> public static XmlDocument PostXMLTransaction(string v_strURL, XmlDocument v_objXMLDoc) { //set max enough to avoid http request is used out -> avoid dead while get response ServicePointManager.DefaultConnectionLimit = 200; XmlDocument XmlResponse = null; HttpWebRequest req; HttpWebResponse rep = null; Stream reqStream = null; //建立一個流對象(用來讀取響應對象的內容) //本文URL地址:http://www.bianceng.cn/Programming/csharp/201410/45571.htm Stream repStream = null; XmlTextReader objXmlReader; //記憶體回收 System.GC.Collect(); req = (HttpWebRequest)WebRequest.Create(v_strURL); try { # region Start HttpRequest byte[] bytes; //傳遞的值 bytes = Encoding.UTF8.GetBytes(v_objXMLDoc.InnerXml); //傳遞的方法,必須要寫,而已Get必須大寫。 req.Method = "POST"; req.ContentLength = bytes.Length; //表頭的格式必須要寫,否則請求響應的頁面得不到要傳遞的值 req.ContentType = "text/xml;encoding='utf-8'"; //把傳遞的值寫到流中 reqStream = req.GetRequestStream(); reqStream.Write(bytes,0,bytes.Length); //必須要關閉請求 reqStream.Close(); #endregion End HttpRequest //建立一個響應對象,並從請求對象中得到響應對象的案例。 rep = (HttpWebResponse)req.GetResponse();//此時程式才開始向目標網頁發送Post請求 //rep = req.GetResponse() as HttpWebResponse; #region Start HttpResponse //HttpStatusCode.OK,指示請求成功,且請求的資訊包含在響應中 if (rep.StatusCode == HttpStatusCode.OK) { //得到回應過來的流 repStream = rep.GetResponseStream(); //Load response stream into XMLReader objXmlReader = new XmlTextReader(repStream); XmlDocument xmldoc = new XmlDocument(); xmldoc.Load(objXmlReader); XmlResponse = xmldoc; objXmlReader.Close(); } //響應關閉,要不會佔用網路資源 rep.Close(); #endregion } catch (WebException we) { //異常處理 } catch (Exception ex) { //異常處理 } finally { //關閉串連 reqStream.Close(); repStream.Close(); rep.Close(); //釋放對象 objXmlReader = null; reqStream = null; repStream = null; rep = null; //objHttpWebRequest = null; if (req!= null) { req.Abort(); } } return XmlResponse; } #endregion
小註:
1、Content-Type:很多時候無法解析就是Content-Type的問題。如果本身就是xml檔案,請跳過這一步
動態產生的XML一定要將其設定為text/xml,否則預設就是text/html也就是普通的文本了。
2、HttpWebRequest在初始化的時候要先根據url進行建立,然後再設定Method和ContentType,然後再將請求的內容寫進去,通過GetRequestStream來返迴流,再向這個流中寫請求內容便可以了。再通過request對象的GetResponse方法返回response對象,最後得到返回的資料流,這是通過GetResponseStream方法返回的,最後從這個流中讀出返回的資料便ok了。
3、ServicePointManager.DefaultConnectionLimit Property:Gets or sets the maximum number of concurrent connections allowed by a ServicePoint object.