函數
/// <summary> /// HttpRequest 請求方式 /// </summary> /// <param name="webUrl">請求地址</param> /// <param name="contentType">請求Context-Type</param> /// <param name="dicPara">請求參數</param> /// <param name="method">請求方式</param> /// <returns>返回請求結果</returns> public string RequestWeb(string webUrl, string contentType, Dictionary<string, string> dicPara = null, string method = "POST") { try { //創建一個請求項 /* * url http://localhost:55563/WMSService.asmx/WMSPushService * url 分爲兩段 * 第一段 webServices 發佈地址 eg:http://localhost:55563/WMSService.asmx * 第二段 將調用webServices的函數名 eg:WMSPushService */ HttpWebRequest request = WebRequest.Create(webUrl) as HttpWebRequest; //判斷服務器是否處理POST的數據 request.ServicePoint.Expect100Continue = method.ToUpper().Equals("POST"); //請求方式 request.Method = method.ToUpper(); //是否建立持久性鏈接 request.KeepAlive = true; //設置HTTP頭 request.UserAgent = "object.yan"; //設置超時時間 request.Timeout = Int32.MaxValue; //設置請求標題頭 request.ContentType = contentType; if (dicPara != null) { //參數經過URL編碼 /* * webService 請求函數中 所包含的參數 必須在paraUrlCoded中進行拼接 * 【且將參數與值進行URL字符串加密】 * 否則將返回 服務器 500 錯誤 */ StringBuilder sbPara = new StringBuilder(); /* * 循環加載參數信息 */ foreach (var item in dicPara) { if (!string.IsNullOrWhiteSpace(sbPara.ToString())) { sbPara.Append("&"); } sbPara.Append(System.Web.HttpUtility.UrlEncode(item.Key)); sbPara.Append("=" + System.Web.HttpUtility.UrlEncode(item.Value)); } /* * 將字符串參數轉爲二進制數組 * 將其寫入請求流中 */ byte[] paraByte; //將URL編碼後的字符串轉化爲字節 paraByte = System.Text.Encoding.UTF8.GetBytes(sbPara.ToString()); //設置請求的ContentLength request.ContentLength = paraByte.Length; //獲得請求流 Stream writer = request.GetRequestStream(); //將請求參數寫入流 writer.Write(paraByte, 0, paraByte.Length); //關閉請求流 writer.Close(); } /* * 獲取webServices返回信息 */ HttpWebResponse response = request.GetResponse() as HttpWebResponse; //讀取資源流信息 StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(response.CharacterSet)); //獲取html文本 return sr.ReadToEnd(); } catch (Exception ex) { return ex.StackTrace + Environment.NewLine + ex.Message; } }
調用函數
Dictionary<string, string> dicPara = new Dictionary<string, string>(); dicPara.Add("logistics_interface", logistics_interface); dicPara.Add("data_digest", data_digest); dicPara.Add("warehouseCode", warehouseCode); RequestWeb("http://localhost:55563/WMSService.asmx/WMSPushService", "application/x-www-form-urlencoded", dicPara)
調用WebServices時 Context-Type使用
application/x-www-form-urlencoded