c# – 如何检查是否配置了代理服务器?
发布时间:2020-12-15 08:45:24 所属栏目:百科 来源:网络整理
导读:当我在Internet Explorer中定义Web代理时,我有一些运行正常的代码.但是,如果没有定义则不起作用.我想检查是否定义了代理.我如何更改以下代码来做到这一点? public DataTable GetCurrentFxPrices(string url){ WebProxy wp = new WebProxy(WebProxy.GetDefau
当我在Internet Explorer中定义Web代理时,我有一些运行正常的代码.但是,如果没有定义则不起作用.我想检查是否定义了代理.我如何更改以下代码来做到这一点?
public DataTable GetCurrentFxPrices(string url) { WebProxy wp = new WebProxy(WebProxy.GetDefaultProxy().Address.AbsoluteUri,true); wp.Credentials = CredentialCache.DefaultCredentials; WebClient wc = new WebClient(); wc.Proxy = wp; MemoryStream ms = new MemoryStream(wc.DownloadData(url)); DataSet ds = new DataSet("fxPrices"); ds.ReadXml(ms); DataTable dt = ds.Tables["Rate"]; int i = dt.Rows.Count; return dt; } 例如,如何在不使用代理的情况下下载数据? UPDATE 我已将代码更改为以下内容 public DataTable GetCurrentFxPrices(string url) { WebClient wc = new WebClient(); if (!String.IsNullOrEmpty(WebProxy.GetDefaultProxy().Address.AbsoluteUri)) { WebProxy wp = new WebProxy(WebProxy.GetDefaultProxy().Address.AbsoluteUri,true); wp.Credentials = CredentialCache.DefaultCredentials; wc.Proxy = wp; } MemoryStream ms = new MemoryStream(wc.DownloadData(url)); DataSet ds = new DataSet("fxPrices"); ds.ReadXml(ms); DataTable dt = ds.Tables["Rate"]; int i = dt.Rows.Count; return dt; } 我得到以下错误System.NullReferenceException未被if语句行上的用户代码处理. 更新2 我也试过更改这一行: if(!String.IsNullOrEmpty(WebProxy.GetDefaultProxy().Address.AbsoluteUri)) 至 if(WebProxy.GetDefaultProxy().Address.AbsoluteUri!= null) 但我得到这个错误: System.NullReferenceException:未将对象引用设置为对象的实例. 有任何想法吗? 解决方法
请记住,您可能没有一个单独的“代理地址”或代理Uri.相反,代理Uri可能依赖于要检索的每个Uri,如Internet Explorer的代理设置对话框中所示.
IWebProxy接口可帮助您获取正确的代理Uri,并告诉您是否将使用或绕过此代理以检索特定的Uri. using System.Net; Uri exampleUri = new Uri("http://www.example.org/") IWebProxy defaultProxy = WebRequest.GetSystemWebProxy(); bool isBypassed = defaultProxy.IsBypassed(exampleUri); // ... false Uri proxyUri = defaultProxy.GetProxy(exampleUri); // ... http://someproxy.mycorp.example:8080 在您的方法中,您必须传递IWebProxy接口,而不是代理地址.默认代理接口(如GetSystemWebProxy)始终设置为默认值. 如果您想设置自己的特殊代理,以防Uri没有代理,您可以执行以下操作… public DataTable GetCurrentFxPrices(string url) { Uri uri = new Uri(url); WebClient webClient = new WebClient(); IWebProxy defaultProxy = WebRequest.GetSystemWebProxy(); IWebProxy myProxy = new WebProxy(new Uri("http://myproxy:8080")) // if no bypass-list is specified,all Uris are to be retrieved via proxy if (defaultProxy.IsBypassed(uri)) { myProxy.Credentials = CredentialCache.DefaultCredentials; webClient.Proxy = myProxy; } MemoryStream ms = new MemoryStream(webClient.DownloadData(url)); DataSet ds = new DataSet("fxPrices"); ds.ReadXml(ms); DataTable dt = ds.Tables["Rate"]; int i = dt.Rows.Count; return dt; } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |