In an C# application, when I try to read an RSS file from Internet using the following code:
WebClient client = new WebClient();
Stream rssStream = client.OpenRead(Url);
StreamReader textReader = new StreamReader(rssStream);
XmlTextReader xmlReader = new XmlTextReader(textReader);
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xmlReader);
It works fine if there is no proxy server setting, but it will report an error when there is proxy server between the local machine and Internet:
An unhandled exception of type 'System.Net.WebException' occurred in system.dll
Additional information: The remote server returned an error: 407 Proxy Authentication Required.
After some investigation to this problem, we found two solutions to read the RSS file correctly.
Using WebClient
If we use WebClient to read the RSS file, we have to tell it what the proxy server setting is, so that it knows how to read the RSS file through the proxy server. The following code demonstrates how to do this:
System.Net.WebProxy proxy = new System.Net.WebProxy(yourproxyserver);
proxy.Credentials = CredentialCache.DefaultCredentials;
//if there is username/password for your proxy server setting, uncomment the following statemtnt instead.
//proxy.Credentials = new NetworkCredential(username, password);
GlobalProxySelection.Select = proxy;
WebClient client = new WebClient();
Stream rssStream = client.OpenRead(Url);
StreamReader textReader = new StreamReader(rssStream);
XmlTextReader xmlReader = new XmlTextReader(textReader);
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xmlReader);
For .NET framework, WebClient offers a new property: Proxy, so you can assign value to this property.
client.Proxy = proxy;
Using WebRequest
You can also use WebRequest to read the RSS file, the key point is the proxy server setting. The following code shows you the usage.
System.Net.WebRequest req = System.Net.WebRequest.Create(Url);
req.Proxy = new System.Net.WebProxy(yourproxyserver, true);
req.Proxy.Credentials = CredentialCache.DefaultCredentials;
System.Net.WebResponse resp = req.GetResponse();
System.IO.StreamReader textReader = new System.IO.StreamReader(resp.GetResponseStream());
XmlTextReader xmlReader = new XmlTextReader(textReader);
XmlDocument xmlDoc= new XmlDocument();
xmlDoc.Load(xmlReader);