HttpWebRequest - 请求终止

时间:2017-02-04 15:07:02

标签: c# asp.net httpwebrequest httpwebresponse connection-timeout

抱歉,我的英语不好。我每10秒使用一次HttpWebRequest。但有时,响应是等待很长时间。 10秒后,接下来的流程即将到来。因此,请求被堆积起来。由于公司在总部采取的措施,我被禁止,因为之前的连接尚未结束。我设置了请求的属性,如Timeout,ContinueTimeout,ReadWriteTimeout,但结果没有改变。实际上,它属于例外。但是当我观看Charles Proxy"时,请求仍在等待响应。但我必须以某种方式阻止它。我分享了我的代码和查尔斯的照片。谢谢你的答案。最好的问候。

Still Wait Response.

        string jsondata = "";
        const string url = "https://website.com";

        HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
        NameValueCollection header_items = GetHeaders();
        req.Headers.Add(header_items);
        req.Method = "POST";
        req.Host = "website.com";
        req.Accept = "application/json, text/plain, */*";
        req.ContentType = "application/json;charset=utf-8";
        req.KeepAlive = false;
        req.UserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)";
        req.Referer = "https://website.com";
        req.AllowAutoRedirect = false;
        req.ContinueTimeout = 5000;
        req.ReadWriteTimeout = 5000;
        req.Timeout = 5000;
        req.ContentLength = 0;
        ServicePointManager.Expect100Continue = true;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11;
        ServicePointManager.DefaultConnectionLimit = 500;
        ServicePointManager.DnsRefreshTimeout = 0;
        ServicePointManager.MaxServicePointIdleTime = 5000;
        ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(delegate { return true; });
        try
        {
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    jsondata = reader.ReadToEnd();
                    reader.Close();
                }
                response.Close();
            }
            if (jsondata.Length > 200)
            {
                //Do Something
            }
        }
        catch (WebException ex)
        {
            req.Abort();
            //Do Something
        }
        catch (Exception ex)
        {
            req.Abort();
            //Do Something
        }

1 个答案:

答案 0 :(得分:0)

尝试为您的请求设置代理设置。很多时候查找代理需要记录HttpWebRequest

req.Proxy = GetSystemWebProxy();

另请看一下:https://en.code-bude.net/2013/01/21/3-things-you-should-know-to-speed-up-httpwebrequest/