Proxy authentication with retry

by alski 4. February 2009 19:55

Need to talk through a proxy? Try this. You'll probably want to refactor in a factory method to allow the correct creation and re-creation of the WebRequest.

Note that attempt one uses the default proxy with Windows authentication parameters, subsequent attempts ask for a user name and password. Or at least they will once you convert the comment into a nice call to a GUI.

int retries = 0; 
bool retry = false; 
 
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://alski.net"); 
HttpWebResponse response = null; 
 
do 
{ 
    try 
    { 
        Console.WriteLine("Attempt " + retries.ToString()); 
        response = (HttpWebResponse)request.GetResponse(); 
 
        Console.WriteLine("Success"); 
    } 
    catch (WebException wex) 
    { 
        Console.WriteLine(wex.Message);
        if ( ((HttpWebResponse)wex.Response).StatusCode == HttpStatusCode.ProxyAuthenticationRequired) 
        { 
            //Can't change proxy after request has been submitted so we recreate the request 
            request = (HttpWebRequest)WebRequest.Create(request.RequestUri);
            switch (retries++) 
            { 
            case 0:
                retry = true; 
                request.Proxy = WebRequest.GetSystemWebProxy();
                break; 
            case 1: 
            case 2: 
            case 3:
                 request.Proxy = WebRequest.DefaultWebProxy; 
                //Show form to ask for credentials and maybe change proxy 
                request.Proxy.Credentials = new NetworkCredential("user", "passsword"); 
                break; 
 
            default: 
                retry = false; 
                break; 
            } 
        } 
    } 
} 
while (response == null 
&& retry); 

Be the first to rate this post

  • Currently 0/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , ,

Code | DotNet2.0

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen

RecentComments

Comment RSS