http串連基礎類,負責底層的http通訊

來源:互聯網
上載者:User

標籤:exce   timeout   int   reading   length   string   start   bytes   伺服器端   

/// <summary>    /// http串連基礎類,負責底層的http通訊    /// </summary>    public class HttpService    {        public static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)        {            //直接確認,否則打不開                return true;        }        public static string Post(string xml, string url, int timeout)        {            System.GC.Collect();//記憶體回收,回收沒有正常關閉的http串連            string result = "";//返回結果            HttpWebRequest request = null;            HttpWebResponse response = null;            Stream reqStream = null;            try            {                //設定最大串連數                ServicePointManager.DefaultConnectionLimit = 200;                //設定https驗證方式                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))                {                    ServicePointManager.ServerCertificateValidationCallback =                            new RemoteCertificateValidationCallback(CheckValidationResult);                }                /***************************************************************                * 下面設定HttpWebRequest的相關屬性                * ************************************************************/                request = (HttpWebRequest)WebRequest.Create(url);                request.Method = "POST";                request.Timeout = timeout * 1000;                //設定Proxy 伺服器                //WebProxy proxy = new WebProxy();                          //定義一個網關對象                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);              //閘道伺服器連接埠:連接埠                //request.Proxy = proxy;                //設定POST的資料類型和長度                request.ContentType = "application/json";                byte[] data = System.Text.Encoding.UTF8.GetBytes(xml);                request.ContentLength = data.Length;                //往伺服器寫入資料                reqStream = request.GetRequestStream();                reqStream.Write(data, 0, data.Length);                reqStream.Close();                //擷取服務端返回                response = (HttpWebResponse)request.GetResponse();                //擷取服務端返回資料                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);                result = sr.ReadToEnd().Trim();                sr.Close();            }            catch (System.Threading.ThreadAbortException e)            {                WriteErrorLog.WriteLogWeb("HttpService,"+ "Thread - caught ThreadAbortException - resetting.");                WriteErrorLog.WriteLogWeb("Exception message: {0}"+ e.Message);                System.Threading.Thread.ResetAbort();            }            catch (WebException e)            {                WriteErrorLog.WriteLogWeb("HttpService,"+ e.ToString());                if (e.Status == WebExceptionStatus.ProtocolError)                {                    WriteErrorLog.WriteLogWeb("HttpService,"+ "StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);                    WriteErrorLog.WriteLogWeb("HttpService,"+ "StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);                }                throw e;            }            catch (Exception e)            {                WriteErrorLog.WriteLogWeb("HttpService,"+ e.ToString());                throw e;            }            finally            {                //關閉串連和流                if (response != null)                {                    response.Close();                }                if (request != null)                {                    request.Abort();                }            }            return result;        }        /// <summary>        /// 處理http GET請求,返回資料        /// </summary>        /// <param name="url">請求的url地址</param>        /// <returns>http GET成功後返回的資料,失敗拋WebException異常</returns>        public static string Get(string url)        {            System.GC.Collect();            string result = "";            WriteErrorLog.WriteLogWeb("HttpService Get 請求地址:"+ url);            HttpWebRequest request = null;            HttpWebResponse response = null;            //請求url以擷取資料            try            {                //設定最大串連數                ServicePointManager.DefaultConnectionLimit = 200;                //設定https驗證方式                if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))                {                    ServicePointManager.ServerCertificateValidationCallback =                            new RemoteCertificateValidationCallback(CheckValidationResult);                }                /***************************************************************                * 下面設定HttpWebRequest的相關屬性                * ************************************************************/                request = (HttpWebRequest)WebRequest.Create(url);                request.Method = "GET";                //設定代理                //WebProxy proxy = new WebProxy();                //proxy.Address = new Uri(WxPayConfig.PROXY_URL);                //request.Proxy = proxy;                //擷取伺服器返回                response = (HttpWebResponse)request.GetResponse();                //擷取HTTP返回資料                StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);                result = sr.ReadToEnd().Trim();                sr.Close();            }            catch (System.Threading.ThreadAbortException e)            {                WriteErrorLog.WriteLogWeb("HttpService"+ ",Thread - caught ThreadAbortException - resetting.");                WriteErrorLog.WriteLogWeb("Exception message: {0}"+ e.Message);                System.Threading.Thread.ResetAbort();            }            catch (WebException e)            {                WriteErrorLog.WriteLogWeb("HttpService"+ e.ToString());                if (e.Status == WebExceptionStatus.ProtocolError)                {                    WriteErrorLog.WriteLogWeb("HttpService"+",StatusCode : " + ((HttpWebResponse)e.Response).StatusCode);                    WriteErrorLog.WriteLogWeb("HttpService"+ ",StatusDescription : " + ((HttpWebResponse)e.Response).StatusDescription);                }                throw e;            }            catch (Exception e)            {                WriteErrorLog.WriteLogWeb("HttpService,"+ e.ToString());                throw e;            }            finally            {                //關閉串連和流                if (response != null)                {                    response.Close();                }                if (request != null)                {                    request.Abort();                }            }            return result;        }    }

  

http串連基礎類,負責底層的http通訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.