当我在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; }
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。