C# HttpWebRequest請求遠程地址獲取返回消息
阿新 • • 發佈:2019-05-03
using mes dict point orm 請求 iter form 超時
HttpWebRequest請求遠程地址獲取返回消息
/// <summary> /// 請求遠程Api獲取響應返回字符串 /// </summary> /// <param name="apiUrl">Api地址</param> /// <param name="parameters">傳遞參數鍵值對</param> /// <param name="contentType">內容類型默認application/x-www-form-urlencodedView Code</param> /// <param name="methord">請求方式默認POST</param> /// <param name="timeout">超時時間默認300000</param> /// <returns>響應字符串</returns> static public object GetHttpWebResponseReturnString(string apiUrl, Dictionary<string, object> parameters, stringcontentType = "application/x-www-form-urlencoded", string methord = "POST", int timeout = 300000) { string result = string.Empty; string responseText = string.Empty; try { if (string.IsNullOrEmpty(apiUrl)) {return DNTRequest.GetResultJson(false, "請求apiURl為空", null); } StringBuilder postData = new StringBuilder(); if (parameters != null && parameters.Count > 0) { foreach (var p in parameters) { if (postData.Length == 0) { postData.AppendFormat("{0}={1}", p.Key, p.Value); } else { postData.AppendFormat("&{0}={1}", p.Key, p.Value); } } } ServicePointManager.DefaultConnectionLimit = int.MaxValue; HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(apiUrl); myRequest.Proxy = null; myRequest.Timeout = timeout; myRequest.ServicePoint.MaxIdleTime = 1000; if (!string.IsNullOrEmpty(contentType)) { myRequest.ContentType = contentType; } myRequest.ServicePoint.Expect100Continue = false; myRequest.Method = methord; byte[] postByte = Encoding.UTF8.GetBytes(postData.ToString()); myRequest.ContentLength = postData.Length; using (Stream writer = myRequest.GetRequestStream()) { writer.Write(postByte, 0, postData.Length); } using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse()) { using (StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8)) { responseText = reader.ReadToEnd(); } } if (!string.IsNullOrEmpty(responseText)) { result = responseText; } else { result = "遠程服務無響應,請稍後再試"; } } catch (Exception ex) { Log.Error(ex.Message); result = "請求異常,請稍後再試"; } return result; }
參考
C# HttpWebRequest請求遠程地址獲取返回消息