HttpWebRequest,HttpWebResponse 使用

 public class HttpRequestAndResponse
    {
        private static readonly string protocol = "http";
        private static readonly string contentType = "application/xml;charset=utf-8";  // Content-Type
        private static readonly string accept = "application/xml";  // Accept
        private static readonly string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022)";  // userAgent

        public HttpRequestAndResponse() { }

        /// <summary>
        /// 调过https验证
        /// </summary>
        private static bool CheckValidationResult(object sender, X509Certificate certificate,
                                              X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }

        public string RequestAndResponse(string url, string requestXML, ref string errString, string encoding = "utf-8", bool isPost = true, int timeOut = 15)
        {
            string response = "";
            HttpWebRequest req = null;
            HttpWebResponse res = null;
            try
            {
                ServicePointManager.ServerCertificateValidationCallback =
                new RemoteCertificateValidationCallback(CheckValidationResult);

                ServicePointManager.DefaultConnectionLimit = 200;//最大并发连接数
                //如果写在配置文件里 app.config
                // <system.net>
                //  <connectionManagement>
                //    <!--表示把对任何域名的请求最大http连接数都设置为200-->
                //    <add address = "*" maxconnection = "200" />
                //  </connectionManagement>
                //</system.net>

                req = WebRequest.Create(url) as HttpWebRequest;

                /*cookie拼接*************************************************************/
                CookieContainer cc = new CookieContainer();
                Cookie cName = new Cookie("name", "");
                cName.Domain = "";
                Cookie cPwd = new Cookie("pwd", "");
                cPwd.Domain = "";
                cc.Add(cName);
                cc.Add(cPwd);
                req.CookieContainer = cc;

                /*HttpWebRequest的基本属性设置*************************************************************/
                req.ProtocolVersion = HttpVersion.Version10;
                req.UserAgent = userAgent;
                req.KeepAlive = false;
                req.Timeout = 1000 * timeOut;
                req.Method = isPost ? "POST" : "GET";
                req.Accept = accept;
                req.ContentType = contentType;

                /*写入http头部信息*************************************************************************/
                req.Headers.Add(string.Format("{0}:{1}", "", ""));

                /*写入requestXML***************************************************************************/
                if (!string.IsNullOrEmpty(requestXML))
                {
                    byte[] bytes = System.Text.Encoding.GetEncoding(encoding).GetBytes(requestXML);
                    if (bytes.Length > 0)
                    {
                        req.ContentLength = bytes.Length;
                        using (Stream reqStream = req.GetRequestStream())
                        {
                            reqStream.Write(bytes, 0, bytes.Length);
                            reqStream.Close();
                        }
                    }
                }

                /*HttpWebResponse获取服务器数据**************************************************************/
                res = req.GetResponse() as HttpWebResponse;
                using (Stream resStream = res.GetResponseStream())
                {
                    using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(encoding)))
                    {
                        response = resStreamReader.ReadToEnd();
                        resStreamReader.Close();
                        resStream.Close();
                    }
                }
            }
            catch (WebException e)
            {
                HttpWebResponse exceptionRes = e.Response as HttpWebResponse;
                errString = "#Status-line\n";
                string format = "protocolVersion:{0}\tstatusCode:{1}\tstatusDescription:{2}\n";
                errString += string.Format(format, exceptionRes.ProtocolVersion, Convert.ToInt32(exceptionRes.StatusCode), exceptionRes.StatusDescription);

                errString += "#Header\n";
                format = "num[{0}]:({1}:{2})\n";
                for (int i = 0; i < exceptionRes.Headers.Count; i++)
                {
                    errString += string.Format(format, i, exceptionRes.Headers.Keys[i], exceptionRes.Headers[i]);
                }

                errString += "#Body\n";
                using (Stream resStream = exceptionRes.GetResponseStream())
                {
                    using (StreamReader resStreamReader = new StreamReader(resStream, Encoding.GetEncoding(encoding)))
                    {
                        errString += resStreamReader.ReadToEnd() + "\n";
                        resStreamReader.Close();
                        resStream.Close();
                    }
                }
                errString += "#end\n";

                exceptionRes.Close();
            }
            catch (Exception e)
            {
                errString = e.ToString();
            }
            finally
            {
                if (req != null)
                {
                    res.Close();
                    res = null;
                }

                if (req != null)
                {
                    req.Abort();
                    req = null;
                }
            }

            return response;
        }
    }

  

目的:工作中已经两次使用了,特此记录一下,并写好注释

时间: 2024-11-25 07:46:31

HttpWebRequest,HttpWebResponse 使用的相关文章

C#网页采集数据的几种方式(WebClient、WebBrowser和HttpWebRequest/HttpWebResponse)

获取网页数据有很多种方式.在这里主要讲述通过WebClient.WebBrowser和HttpWebRequest/HttpWebResponse三种方式获取网页内容. 这里获取的是包括网页的所有信息.如果单纯需要某些数据内容.可以自己构造函数甄别抠除出来!一般的做法是根据源码的格式,用正则来过滤出你需要的内容部分. 一.通过WebClient获取网页内容 这是一种很简单的获取方式,当然,其它的获取方法也很简单.在这里首先要说明的是,如果为了实际项目的效率考虑,需要考虑在函数中分配一个内存区域.

【转】C# HttpWebRequest\HttpWebResponse\WebClient发送请求解析json数据

http://blog.csdn.net/kingcruel/article/details/44036871 版权声明:本文为博主原创文章,未经博主允许不得转载. [csharp] view plain copy ====================================================================================================================================== /// <su

HttpWebRequest / HttpWebResponse 远程获取文件信息

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(path+filename); //创建一个请求(获得需要的文件信息) HttpWebResponse myRes = (HttpWebResponse)myReq.GetResponse(); string gorlseftDate = myRes.LastModified.ToString("yyyy-MM-dd hh:mm:ss");//获得dataServer.ra

MSDN中HttpWebRequest/HttpWebResponse用法

HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create("http://home.cnblogs.com/u/weiweiboqi/"); HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse(); Stream receiveStream = HttpWResp.GetResponseStream(); Encoding encode = System.T

HttpWebRequest,HttpWebResponse C# 代码调用webservice,参数为xml

先上调用代码 1 public static string PostMoths(string url, string Json) 2 { 3 System.Net.HttpWebRequest request; 4 Stream writer; 5 System.Net.HttpWebResponse response; 6 7 try 8 { 9 string strURL = url; 10 System.GC.Collect(); 11 System.Net.ServicePointMan

HttpWebRequest 和 HttpWebResponse 的应用

转载:http://www.cnblogs.com/yiki/archive/2007/08/28/872528.html HttpWebRequest request = (HttpWebRequest)WebRequest.Create(addr);// Downloads the XML file from the specified server.HttpWebResponse response = (HttpWebResponse)request.GetResponse();Syste

HttpWebRequest 和HttpWebResponse总结

1. 总结 总结2 3. Code using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; using System.Web; namespace Core { public class RequestHelper { private Stream Se

C#中HttpWebRequest与HttpWebResponse的使用方法

关键字:C# HttpWebRequest HttpWebResponse HTTP GET POST 请求 这个类是专门为HTTP的GET和POST请求写的,解决了编码,证书,自动带Cookie等问题.C# HttpHelper,帮助类,真正的Httprequest请求时无视编码,无视证书,无视Cookie,网页抓取 1.第一招,根据URL地址获取网页信息   先来看一下代码get方法 public static string GetUrltoHtml(string Url,string ty

HttpWebRequest

同步请求===================================================================================== byte[] data = System.Text.Encoding.UTF8.GetBytes("data=Hello,World~");//组建要提交的数据 HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://lo