WebProxy测试连接异常行为

时间:2018-12-11 20:51:52

标签: c# httpclient webclient networkcredentials webproxy

我正在编写一个功能来测试代理服务器连接。用户需要填写网络表单,并需要提供以下信息:

  1. 代理服务器IP地址
  2. 代理服务器端口
  3. 如果需要验证,请选中一个复选框
  4. 如果选中了身份验证复选框,则用户需要提供用户名和密码。

我用于单元测试的代理服务器需要身份验证。

它在以下两种情况下都适用:抛出异常:

  1. TestProxy.TestProxySettingsWithWebclient(URL,“ Correct_IP_Address”,“ Correct_Port”,false); //由于需要身份验证将抛出错误
  2. TestProxy.TestProxySettingsWithWebclient(URL,“ Correct_IP_Address”,“ Correct_Port”,true,“ Incorrect_Username”,“ Incorrect_Password”); //由于需要验证,将抛出错误

我得到的奇怪行为是,当我执行以下操作时:

  1. 我使用正确的IP和正确的凭据调用该方法-TestProxy.TestProxySettingsWithWebclient(URL,“ Correct_IP_Address”,“ Correct_Port”,true,“ Correct_Username”,“ Correct_Password”);。一切都会正确,它不会失败。
  2. 然后,我尝试使用正确的IP并且没有凭据。 TestProxy.TestProxySettingsWithWebclient(url,“ Correct_IP_Address”,“ Correct_Port”,false);。它通过了,没有异常发生,这是错误的,因为此代理服务器需要身份验证。 d
  3. 然后,我尝试使用正确的IP并且没有凭据。 TestProxy.TestProxySettingsWithWebclient(URL,“ Correct_IP_Address”,“ Correct_Port”,true,“ Incorrect_Username”,“ Incorrect_Password”);。它也不会抛出任何错误的异常。

基本上,一旦我使用了正确的IP,正确的端口,正确的用户名和密码,然后在此之后,如果尝试使用相同的IP和相同的端口但使用了错误的凭据,或者没有凭据,则测试将始终通过且不会发生异常。哪有错。

有人可以告诉我我在做什么错吗?

以下是我编写的用于测试代理服务器连接的功能:

public static bool TestProxySettings(string urlToHit, string proxyAddress, int? port,
        bool isAuthenticationRequired,
        string userName = null, string password = null)
    {
        string url = urlToHit + "?time=" + DateTime.Now.Ticks;
        NetworkCredential networkCredential = null;

        if (port.HasValue)
            proxyAddress += ":" + port.Value;

        if (isAuthenticationRequired)
            networkCredential = new NetworkCredential(userName, password);

        try
        {
            WebProxy proxy = new WebProxy(proxyAddress)
            {
                UseDefaultCredentials = false,
                BypassProxyOnLocal = false,
                Credentials = networkCredential
            };

            using (WebClient client = new WebClient())
            {
                client.CachePolicy = new RequestCachePolicy(RequestCacheLevel.NoCacheNoStore);
                client.Proxy = new WebProxy();
                client.Proxy = proxy;
                var downloadString = client.DownloadString(url);
            }
        }
        catch (WebException ex)
        {
            // ex.Response will be null if it fails at proxy server level
            if (ex.Response == null || ((HttpWebResponse) ex.Response).StatusCode ==
                HttpStatusCode.ProxyAuthenticationRequired)
            {
                Console.Write(@"An error has occurred while contacting the proxy server: ""{0}""", ex.Message);
            }
            else
            {
                Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""",
                    url, ex.Message);
            }

            return false;
        }
        catch (Exception ex)
        {
            Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""", url,
                ex.Message);

            return false;
        }

        return true;
    }

注意:我尝试使用HttpClient和HttpWebRequest,但是存在相同的问题。

以HttpClient为例:

public static bool TestProxySettingsWithHttpClient(string urlToHit, string proxyAddress, int? port,
            bool isAuthenticationRequired,
            string userName = null, string password = null)
        {
            string url = urlToHit + "?time=" + DateTime.Now.Ticks;
            NetworkCredential networkCredential = null;

            if (port.HasValue)
            {
                proxyAddress += ":" + port.Value;
            }

            if (isAuthenticationRequired)
                networkCredential = new NetworkCredential(userName, password);

            try
            {
                WebProxy proxy = new WebProxy(proxyAddress)
                {
                    UseDefaultCredentials = false,
                    BypassProxyOnLocal = false,
                    Credentials = networkCredential
                };

                using (var handler = new HttpClientHandler() {Proxy = proxy, UseProxy = true})
                using (HttpClient client = new HttpClient(handler) {BaseAddress = new Uri(urlToHit)})
                {
                    var downloadString = client.GetAsync("/").Result;
                }
            }
            catch (WebException ex)
            {
                // ex.Response will be null if it fails at proxy server level
                if (ex.Response == null || ((HttpWebResponse) ex.Response).StatusCode ==
                    HttpStatusCode.ProxyAuthenticationRequired)
                {
                    Console.Write(@"An error has occurred while contacting the proxy server: ""{0}""", ex.Message);
                }
                else
                {
                    Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""",
                        url, ex.Message);
                }

                return false;
            }
            catch (Exception ex)
            {
                Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""", url,
                    ex.Message);

                return false;
            }

            return true;
        }

以下是HttpWebRequest和HttpWebResponse的示例:

public static bool TestProxySettingsWithHttpWebRequest(string urlToHit, string proxyAddress, int? port,
            string userName, string password, bool isAuthenticationRequired)
        {
            string url = urlToHit + "?time=" + DateTime.Now.Ticks;
            var uriBuilder = new UriBuilder(url);
            NetworkCredential networkCredential = null;
            HttpWebRequest request = null;
            WebProxy proxy = null;
            var timeoutSettings = 50000;

            if (port.HasValue)
            {
                proxyAddress += ":" + port.Value;
            }

            if (isAuthenticationRequired)
            {
                networkCredential = new NetworkCredential(userName, password);
            }

            try
            {
                request = (HttpWebRequest) WebRequest.Create(uriBuilder.Uri);

                proxy = new WebProxy(proxyAddress);
                proxy.UseDefaultCredentials = false;
                proxy.BypassProxyOnLocal = false;
                proxy.Credentials = networkCredential;

                request.Timeout = timeoutSettings;
                request.Accept = "*/*";
                request.KeepAlive = false;
                request.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.NoCacheNoStore);
                request.Proxy = proxy;

                using (HttpWebResponse response = (HttpWebResponse) request.GetResponse())
                {
                    // no action required
                }
            }
            catch (WebException ex)
            {
                // ex.Response will be null if it fails at proxy server level
                if (ex.Response == null || ((HttpWebResponse) ex.Response).StatusCode ==
                    HttpStatusCode.ProxyAuthenticationRequired)
                {
                    Console.Write(@"An error has occurred while contacting the proxy server: ""{0}""", ex.Message);
                }
                else
                {
                    Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""",
                        url, ex.Message);
                }

                return false;
            }
            catch (Exception ex)
            {
                Console.Write(@"An error has occurred while contacting ""{0}"" using the proxy server: ""{1}""", url,
                    ex.Message);

                return false;
            }
            finally
            {
                request = null;
            }

            return true;
        }

0 个答案:

没有答案