Download Files using HTTP and Proxy Server in C#


This article is an extension to article Using WebRequest and WebResponse Classes to download files using HTTP, I wrote in year 2001. One user at C# Corner asked me a question, how to download files using HTTP by passing Proxy server. This article explains how to pass proxy server network credentials when downloading files using HTTP.

Passing Network Credentials

If your company is using proxy server to connect to the Internet, you will have to pass proxy settings to download files from the Internet using HTTP. To do so, you need to create a WebProxy instance, and set its Credentials property, which is NetworkCredential and takes userId, password, and network domain.

Here is the code that uses network credentials:

string result = "";
try
{
WebProxy proxy = new WebProxy("http://proxy:80/", true);
proxy.Credentials = new NetworkCredential("userId", "password", "Domain");
WebRequest request = WebRequest.Create(http://www.c-sharpcorner.com);
request.Proxy = proxy;
// Send the 'HttpWebRequest' and wait for response.
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); System.IO.Stream stream = response.GetResponseStream();
System.Text.Encoding ec = System.Text.Encoding.GetEncoding("utf-8");
System.IO.StreamReader reader = new System.IO.StreamReader(stream, ec);
char [] chars = new Char[256];
int count = reader.Read(chars, 0, 256);
while(count > 0)
{
string str = new String(chars, 0, 256);
result = result + str;
count = reader.Read(chars, 0, 256);
}
response.Close();
stream.Close();
reader.Close();
}
catch(Exception exp)
{
string str = exp.Message;
}

Using HTTPS with WebProxy Class

When you create a WebProxy class instance for a proxy server to pass proxy to download files from the Internet using HTTP, code looks like this:

WebProxy proxy = new WebProxy("http://proxy:80/", true);

However, this code will not work when you want to download a file from HTTPS. You need to use the following code to create a WebProxy instance for HTTPS:

WebProxy myProxy = new WebProxy("server.https.com", 443);


Similar Articles
Mindcracker
Founded in 2003, Mindcracker is the authority in custom software development and innovation. We put best practices into action. We deliver solutions based on consumer and industry analysis.