HttpWebRequest.GetResponse()操作超时

    在项目中调用了一条比较复杂的sql 写的web api,调用的时候经常操作超时。

 

   修改HttpWebRequest.Timeout与HttpWebRequest.KeepAlive

   具体相关代码如下:

     /// <summary>  
        /// 创建GET方式的HTTP请求  
        /// </summary>  
        public static HttpWebResponse CreateGetHttpResponse(string url, int timeout, string userAgent, CookieCollection cookies)
        {
            HttpWebRequest request = null;
            if (url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                //对服务端证书进行有效性校验(非第三方权威机构颁发的证书,如自己生成的,不进行验证,这里返回true)
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                request = WebRequest.Create(url) as HttpWebRequest;
                request.ProtocolVersion = HttpVersion.Version10;    //http版本,默认是1.1,这里设置为1.0
            }
            else
            {
                request = WebRequest.Create(url) as HttpWebRequest;
            }
            request.Method = "GET";

            //设置代理UserAgent和超时
            //request.UserAgent = userAgent;
            //request.Timeout = timeout;
            if (cookies != null)
            {
                request.CookieContainer = new CookieContainer();
                request.CookieContainer.Add(cookies);
            }
            try
            {
                request.Timeout = Timeout.Infinite;
                request.KeepAlive = true;
                return request.GetResponse() as HttpWebResponse;
            }
            catch (WebException ex)
            {
                return (HttpWebResponse)ex.Response;

            }
        }

 

posted @ 2020-02-18 14:40  binzi-6  阅读(2446)  评论(0编辑  收藏  举报