/// <summary> /// post 报文到接口服务器 /// </summary> /// <param name="targetUri">路径</param> /// <param name="content">提交的报文</param> /// <returns>返回报文</returns> public static string PostData(string targetUri, string content) { HttpWebRequest httpRequest = null; HttpWebResponse hwr = null; System.IO.Stream requestStream = null; System.IO.Stream responseStream = null; try { Encoding encoding = Encoding.GetEncoding("utf-8"); byte[] bytesToPost = encoding.GetBytes(content); string cookieheader = string.Empty; CookieContainer cookieCon = new CookieContainer(); System.GC.Collect(); //垃圾回收 System.Net.ServicePointManager.DefaultConnectionLimit = 100; //允许的最大并发数 #region 创建HttpWebRequest对象 httpRequest = (HttpWebRequest)WebRequest.Create(targetUri); #endregion #region 初始化HtppWebRequest对象 httpRequest.CookieContainer = cookieCon; httpRequest.UserAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)"; httpRequest.ContentType = "application/x-www-form-urlencoded"; httpRequest.Method = "POST"; httpRequest.Headers.Add("Accept-Encoding", "gzip, deflate"); if (cookieheader.Equals(string.Empty)) { cookieheader = httpRequest.CookieContainer.GetCookieHeader(new Uri(targetUri)); } else { httpRequest.CookieContainer.SetCookies(new Uri(targetUri), cookieheader); } #endregion #region 附加Post给服务器的数据到HttpWebRequest对象 httpRequest.ContentLength = bytesToPost.Length; requestStream = httpRequest.GetRequestStream(); requestStream.Write(bytesToPost, 0, bytesToPost.Length); requestStream.Close(); #endregion #region 读取服务器返回信息 hwr = (HttpWebResponse)httpRequest.GetResponse(); string xzip = hwr.ContentEncoding; responseStream = hwr.GetResponseStream(); string stringResponse = ""; if (xzip == "gzip") { //压缩,进行解压缩处理 } else { using (System.IO.StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8)) { stringResponse = responseReader.ReadToEnd(); } } #endregion return stringResponse; } catch (Exception ex) { return ""; } finally { #region 关闭相应连接 if (requestStream != null) { requestStream.Close(); requestStream = null; } if (responseStream != null) { responseStream.Close(); responseStream = null; } if (hwr != null) { hwr.Close(); hwr = null; } if (httpRequest != null) { httpRequest.Abort(); httpRequest = null; } #endregion } }