HTTP

The .NET Framework provides comprehensive support for the HTTP protocol, which makes up the majority of all Internet traffic, with theHttpWebRequest and HttpWebResponse classes. These classes, derived from WebRequest and WebResponse, are returned by default whenever the static method WebRequest.Create encounters a URI beginning with "http" or "https". In most cases, the WebRequest and WebResponse classes provide all that is necessary to make the request, but if you need access to the HTTP-specific features exposed as properties, you can typecast these classes to HttpWebRequest or HttpWebResponse.

HttpWebRequest and HttpWebResponse encapsulate a standard HTTP request-and-response transaction and provide access to common HTTP headers. These classes also support most HTTP 1.1 features, including pipelining, chunking, authentication, preauthentication, encryption, proxy support, server certificate validation, and connection management. Custom headers and headers not provided through properties can be stored in and accessed through the Headers property.

The following sample shows how to access HTTP-specific properties, in this case to turn off the HTTP Keep-alive behavior and get the protocol version number from the Web server.

Dim HttpWReq As HttpWebRequest= _
    CType(WebRequest.Create("https://www.contoso.com"), HttpWebRequest)
' Turn off connection keep-alives.
HttpWReq.KeepAlive = False

Dim HttpWResp As HttpWebResponse = _
    CType(HttpWReq.GetResponse(), HttpWebResponse)

' Get the HTTP protocol version number returned by the server.
Dim ver As String = HttpWResp.ProtocolVersion.ToString()
HttpWResp.Close()
[C#]
HttpWebRequest HttpWReq = 
    (HttpWebRequest)WebRequest.Create("https://www.contoso.com");
// Turn off connection keep-alives.
HttpWReq.KeepAlive = false;

HttpWebResponse HttpWResp = (HttpWebResponse)HttpWReq.GetResponse();

// Get the HTTP protocol version number returned by the server.
String ver = HttpWResp.ProtocolVersion.ToString();
HttpWResp.Close();

HttpWebRequest is the default class used by WebRequest and does not need to be registered before you can pass a URI to the WebRequest.Create method.

You can make your application follow HTTP redirects automatically by setting the AllowAutoRedirect property to true (the default). The application will redirect requests, and the ResponseURI property of HttpWebResponse will contain the actual Web resource that responded to the request. If you set AllowAutoRedirect to false, your application must be able to handle redirects as HTTP protocol errors.

Applications receive HTTP protocol errors by catching a WebException with the Status set to WebExceptionStatus.ProtocolError. The Response property contains the WebResponse sent by the server and indicates the actual HTTP error encountered.

See Also

Accessing the Internet Through a Proxy | Using Application Protocols