C# – error (407) “Proxy Authentication Required.”

authenticationchttpwebrequest

I have a requirement like…i want to access an url (login page which is web) from a winforms. i have to pass the credentials to that url and the response should be the contect of the authenticated web page(markup).

I have written a function which will request the url and return the response. but i am getting error code (407)

"Proxy Authentication Required."

Here is my code.

private static void GetPageContent(){
    string url = "https://LoginPage.aspx/";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = "GET";
    // If required by the server, set the credentials.
    //request.Proxy.Credentials = CredentialCache.DefaultCredentials;
    request.Credentials = new NetworkCredential("user1", "testuser#");
    // Get the response.
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    // Display the status.
    Console.WriteLine(response.StatusDescription);
    // Get the stream containing content returned by the server.
    Stream dataStream = response.GetResponseStream();
    // Open the stream using a StreamReader for easy access.
    StreamReader reader = new StreamReader(dataStream);
    // Read the content.
    string responseFromServer = reader.ReadToEnd();
    // Display the content.
    Console.WriteLine(responseFromServer);
    // Cleanup the streams and the response.
    reader.Close();
    dataStream.Close();
    response.Close();
}

Best Answer

WebProxy proxy = new WebProxy(proxyAddress);
proxy.Credentials = new NetworkCredential("username", "password", "domain");
proxy.UseDefaultCredentials = true;
WebRequest.DefaultWebProxy = proxy;

HttpWebRequest request = new HttpWebRequest();
request.Proxy = proxy;

Or you could use WebClient.

WebClient client = new WebClient();
client.Proxy = proxy;
string downloadString = client.DownloadString("http://www.google.com");
Related Topic