web 2.0

(407) proxy authentication required : Use HttpWebRequest with Proxy

Hi,

Today i'll talking about HttpWebRequest and WebProxies. Here is a quick sample of code in order to set a WebProxy on HttpWebRequest.

MSDN : HttpWebRequest

HttpWebRequest Class
Provides an HTTP-specific implementation of the WebRequest class.

The HttpWebRequest class provides support for the properties and methods defined in WebRequest and for additional properties and methods that enable the user to interact directly with servers using HTTP.

Do not use the HttpWebRequest constructor. Use the System.Net.WebRequest.Create method to initialize new HttpWebRequest objects. If the scheme for the Uniform Resource Identifier (URI) is http:// or https://, Create returns an HttpWebRequest object.

MSDN : HttpWebResponse

HttpWebResponse Class
Provides an HTTP-specific implementation of the WebResponse class.

This class contains support for HTTP-specific uses of the properties and methods of the WebResponse class. The HttpWebResponse class is used to build HTTP stand-alone client applications that send HTTP requests and receive HTTP responses.

Do not confuse HttpWebResponse with the HttpResponse class that is used in ASP.NET applications and whose methods and properties are exposed through ASP.NET's intrinsic Response object.

MSDN : WebProxy

WebProxy Class
Contains HTTP proxy settings for the WebRequest class.

The WebProxy class contains the proxy settings that WebRequest instances use to determine whether a Web proxy is used to send requests. Global Web proxy settings can be specified in machine and application configuration files, and applications can use instances of the WebProxy class to customize Web proxy use. The WebProxy class is the base implementation of the IWebProxy interface.

Here is the sample of using WebProxy with HttpWebRequest

static void Main(string[] args)
{
    String Url = "http://www.google.com";
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);

    // Get Default Proxy
    IWebProxy proxy = WebRequest.GetSystemWebProxy();
    if (proxy != null && proxy.Credentials != null)
    {
        request.Proxy = proxy;
    }
    else
    {
        // Create new Proxy
        proxy = new WebProxy("myproxy:8080");

        // Set Credentials
        proxy.Credentials = new NetworkCredential("user", "password");
        request.Proxy = proxy;
    }

    // Get Response and Write Contents to the Console
    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        Console.WriteLine(sr.ReadToEnd());
    }
}

Hope this help's!



Views(2651)

kick it on DotNetKicks.com

Share/Save/Bookmark Subscribe

Be the first to rate this post

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

Tags:

C#

Comments

Add comment


 

biuquote
Loading



Technorati Profile