How to get proxy

2.2k views Asked by At

I try to get proxy for web request (HttpWebRequest or webclient) In control panel->Internet Options->Connecitons->LAN Settings you will see 3 options:

  1. Automatically detect settings
  2. Use automatic configuration script
  3. Use a proxy server for your LAN

I want to make sure no matter whichever setting, my web request pick up the same proxy as browser does.

I am using the code below to achieve this; however, when 1. is checked, I try the same URL in browser and my code, it looks my code is much slower. I guess the way I get proxy in code may be not efficient or appropriate.

Is there anything I can change in my code to mirror the speed of the browser?

    var client = (HttpWebRequest)WebRequest.Create(uriStr);
    client.Headers["something"] = something;
    client.Timeout = ConnectionTimeOut; //1 min 

    var proxyURI = WebRequest.GetSystemWebProxy().GetProxy(uri);
    var proxy = new WebProxy(proxyURI, true)
    {
        Credentials = CredentialCache.DefaultNetworkCredentials
    };
    //if there is no proxy, proxy will return the same uri
    //do we need check if client.Proxy is null or not,
    if (proxyURI != null && !string.IsNullOrEmpty(proxyURI.AbsoluteUri) && !proxy.Address.Equals(uri))
    {
        client.Proxy = proxy;
    }
1

There are 1 answers

0
Aaron McIver On

Your approach is fine.

What may be causing the speed difference is that the browser may have either cached the page you are requesting or cached the proxy/proxy credentials and does not need to perform any net new fetching as you are performing within your code.

Have you tried subsequent requests within your application after acquiring the proxy/credentials?