Tôi có một số mã chạy tốt khi tôi có proxy web được xác định trong Internet Explorer. Tuy nhiên nếu không có định nghĩa nào thì nó không hoạt động. Tôi muốn kiểm tra xem proxy có được xác định không. Làm thế nào tôi có thể thay đổi mã dưới đây để làm điều đó?Cách kiểm tra xem máy chủ proxy có được định cấu hình không?
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;
}
Ví dụ: làm cách nào để tải xuống dữ liệu mà không sử dụng proxy?
CẬP NHẬT
Tôi đã thay đổi mã như sau
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;
}
tôi nhận được lỗi sau System.NullReferenceException was unhandled by user code
trên nếu dòng tuyên bố.
UPDATE 2
Tôi cũng đã cố gắng thay đổi dòng này:
if (!String.IsNullOrEmpty(WebProxy.GetDefaultProxy().Address.AbsoluteUri))
để
if (WebProxy.GetDefaultProxy().Address.AbsoluteUri != null)
nhưng tôi nhận được lỗi này:
System.NullReferenceException: Object reference not set to an instance of an object.
Bất kỳ ý tưởng nào?
Nếu không có proxy: Sẽ bỏ qua 'wc.Proxy = wp;' làm thủ thuật? ("nếu không có proxy, không đặt nó") – Piskvor
Bạn có biết rằng WebProxy.GetDefaultProxy() được coi là lỗi thời? Bạn nên sử dụng WebRequest.GetSystemWebProxy() hoặc WebRequest.DefaultWebProxy thay thế. –
Tôi đã cập nhật câu hỏi của mình để sử dụng 'GetSystemWebProxy'. Vẫn còn gặp khó khăn, bạn có thể xem không? –