How to perform a fast web request in C#

前端 未结 4 458
夕颜
夕颜 2020-12-16 09:59

I have a HTTP based API which I potentially need to call many times. The problem is that I can\'t get the request to take less than about 20 seconds, though the same reques

相关标签:
4条回答
  • 2020-12-16 10:38

    Does your site have an invalid SSL cert? Try adding this

    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AlwaysAccept);
    
    //... somewhere AlwaysAccept is defined as:
    
    using System.Security.Cryptography.X509Certificates;
    using System.Net.Security;
    
    public bool AlwaysAccept(object sender, X509Certificate certification, X509Chain chain, SslPolicyErrors sslPolicyErrors)
    {
        return true;
    }
    
    0 讨论(0)
  • 2020-12-16 10:39

    This problem is similar to another post on StackOverflow: Stackoverflow-2519655(HttpWebrequest is extremely slow)

    Most of the time the problem is the Proxy server property. You should set this property to null, otherwise the object will attempt to search for an appropriate proxy server to use before going directly to the source. Note: this property is turn on by default, so you have to explicitly tell the object not to perform this proxy search.

    request.Proxy = null;
    using (var response = (HttpWebResponse)request.GetResponse())
    {
    }
    
    0 讨论(0)
  • 2020-12-16 10:51

    You don't close your Request. As soon as you hit the number of allowed connections, you have to wait for the earlier ones to time out. Try

    using (var response = g.GetResponse())
    {
        // do stuff with your response
    }
    
    0 讨论(0)
  • 2020-12-16 10:53

    I was having the 30 second delay on 'first' attempt - JamesR's reference to the other post mentioning setting proxy to null solved it instantly!

    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(_site.url);
    request.Proxy = null; // <-- this is the good stuff
    
    ...
    
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    
    0 讨论(0)
提交回复
热议问题