当我在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;
}
Run Code Online (Sandbox Code Playgroud)
例如,如何在不使用代理的情况下下载数据?
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;
}
Run Code Online (Sandbox Code Playgroud)
我System.NullReferenceException was unhandled by user code在if语句行上得到以下错误.
更新2
我也试过更改这一行:
if (!String.IsNullOrEmpty(WebProxy.GetDefaultProxy().Address.AbsoluteUri))
至
if (WebProxy.GetDefaultProxy().Address.AbsoluteUri != null)
但我得到这个错误:
System.NullReferenceException: Object reference not set to an instance of an object.
有任何想法吗?
ole*_*hri 10
请记住,您可能没有一个单独的"代理地址"或代理Uri.相反,代理Uri可能依赖于要检索的每个Uri,如Internet Explorer的代理设置对话框中所示.

该IWebProxy界面可以帮助您得到正确的代理服务器开放的,并告诉你,如果这个代理会被使用或者绕过一个特定的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
Run Code Online (Sandbox Code Playgroud)
在您的方法中,您必须传递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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12686 次 |
| 最近记录: |