Using Internet Request and Response Classes

To request data from the Internet and read the response, complete the following steps

  1. If you are accessing a resource such as a Web page, create a WebRequest by calling WebRequest.Create with the URI of the resource you want to use, as in the following example.

    WebRequest wReq = WebRequest.Create("https://www.contoso.com/");
    [Visual Basic]
    Dim wReq as WebRequest = WebRequest.Create("https://www.contoso.com/")
    

    **Note   **The .NET Framework provides protocol-specific WebRequest and WebResponse descendants for URIs that begin with "http:", "https:'', and "file:". To access other protocols, you must implement protocol-specific descendants of WebRequest and WebResponse. For more information, see Programming Pluggable Protocols.

  2. Set any property values that you need in the WebRequest. For example, to support authentication, set the Credentials property to an instance of the NetworkCredential class, as in the following example.

    wReq.Credentials = CredentialCache.DefaultCredential;
    [Visual Basic]
    wReq.Credentials CredentialCache.DefaultCredential
    

    In most cases, the WebRequest itself is sufficient to send and receive data. However, if you need to set protocol-specific properties, typecast the WebRequest to the protocol-specific instance. The typecast will be valid only if the correct WebRequest descendant is handling the WebRequest. For example, to access the HTTP-specific properties of HttpWebRequest, typecast the WebRequest to HttpWebRequest. The following code example shows how to set the HTTP-specific UserAgent property.

    if (wReq is HttpWebRequest) 
    {
       ((HttpWebRequest)wReq).UserAgent = ".NET Framework Example Client";
    }
    [Visual Basic]
    If TypeOf wReq is HttpWebRequest Then
       Ctype(wReq,HttpWebRequest).UserAgent = _
          ".NET Framework Example Client"
    End If
    
  3. To download a resource from the Internet, call the GetResponse method of your WebRequest.

    To send or upload data to a resource, call the GetRequestStream method of your WebRequest and use the resulting Stream object to write the data. When you have finished uploading, you must close the request stream with the Stream.Close method. After closing the stream, you can call GetResponse to ensure that the server received the data correctly. The actual class of the WebResponse instance returned is determined by the scheme of the requested URI. The following code example shows how to create a WebResponse using the GetResponse method.

    WebResponse wResp = wReq.GetResponse();
    [Visual Basic]
    Dim wResp As WebResponse = wReq.GetResponse()
    

    Note   Once you call WebResponse, you must close the response with WebResponse.Close or Stream.Close. If you do not close each response, your application will run out of connections to the server and be unable to process additional requests.

  4. Use the GetResponseStream method of the WebResponse to get the stream containing response data from the network resource. You can also access the properties of the WebResponse or typecast the WebResponse to a protocol-specific instance to read protocol-specific properties. For example, to access the HTTP-specific properties of HttpWebResponse, typecast WebResponse to HttpWebResponse. The following code example shows how to access an HTTP-specific property and read the response stream.

    // Read an HTTP-specific property.
    if (wResp is HttpWebResponse) 
    {
       DateTime Updated = ((HttpWebResponse)wResp).LastModified;
    }
    // Get the response stream.
    Stream respStream = wResp.GetResponseStream();
    
    // This example uses a StreamReader to read the entire response
    // into a string and then writes the string to the console.
    StreamReader reader = new StreamReader(respStream, Encoding.ASCII);
    String respHTML = reader.ReadToEnd();
    Console.WriteLine(respHTML);
    
    // Close the response stream.
    respStream.Close();
    [Visual Basic]
    ' Read an HTTP-specific property.
    If TypeOf wResp Is HttpWebResponse Then
      Dim updated As DateTime = Ctype(wResp,HttpWebResponse).LastModified
    End If
    
    ' Get the response stream.
    Dim respStream As Stream = wResp.GetResponseStream()
    
    ' This example uses a StreamReader to read the entire response
    ' into a string and then writes the string to the console.
    Dim reader As StreamReader = _
       New StreamReader(respStream, Encoding.ASCII)
    Dim respHTML as String = reader.ReadToEnd()
    Console.WriteLine(respHTML)
    
    ' Close the response stream
    respStream.Close()
    

    If your application requires only the header information returned in the WebResponse and ignores any returned data, you do not need to get the response stream. The following code example shows how to return the server header information from an Internet host.

    WebRequest wReq = WebRequest.Create("https://www.contoso.com");
    WebResponse wResp = wReq.GetResponse();
    string server = wResp.Headers["Server"];
    [Visual Basic]
    Dim wReq As WebRequest = WebRequest.Create("https://www.contoso.com")
    Dim wResp As WebResponse = wReq.GetResponse()
    Dim server As String = wResp.Headers("Server")
    
  5. After reading the data from the response, you must either close any opened stream using the Stream.Close method or close the response using the WebResponse.Close method.

    wResp.Close();
    [Visual Basic]
    wResp.Close()
    

    It is not necessary to call the Close method on both the response stream and the WebResponse, but doing so is not harmful. WebResponse.Close calls Stream.Close when closing the response.

    The following example application demonstrates how to use the WebRequest and WebResponse classes.

    using System;
    using System.Net;
    using System.Text;
    using System.IO;
    
    class ClientGet {
       public static void Main(string[] args)
       {
          if (args.Length < 1)
          {
            showusage();
            return;
          }
    
          // Get the URI from the command line.
          Uri site = new Uri(args[0]);
    
          // Create the request instance.
          WebRequest wReq = WebRequest.Create(site);
    
          // Set the HTTP-specific UserAgent property
          if (wReq is HttpWebRequest) 
          {
            ((HttpWebRequest)wReq).UserAgent = 
              ".NET Framework Example Client";
          }
    
          // Get the response instance
          WebResponse wResp = wReq.GetResponse();
    
          // Read an HTTP-specific property.
          if (wResp is HttpWebResponse)
          {
            DateTime updated = ((HttpWebResponse)wResp).LastModified;
          }
    
          // Get the response stream.
          Stream respStream = wResp.GetResponseStream();
    
         // This example uses a StreamReader to read the entire response
         // into a string and then writes the string to the console.
         StreamReader reader = 
           new StreamReader(respStream, Encoding.ASCII);
         String respHTML = reader.ReadToEnd();
         Console.WriteLine(respHTML);
    
         // Close the response and response stream.
         wResp.Close();
       }
       public static void showusage()
       {
          Console.WriteLine("Attempts to GET a URI.");
          Console.WriteLine("\r\nUsage:");
          Console.WriteLine("  ClientGet URI");
          Console.WriteLine("Example:");
          Console.WriteLine("  ClientGet https://www.contoso.com/");
       }
    }
    [Visual Basic]
    Imports System
    Imports System.Net
    Imports System.IO
    Imports System.Text
    Imports Microsoft.VisualBasic
    
    Class ClientGet
    Public Shared Sub Main()
      Dim Args() As String = System.Environment.GetCommandLineArgs()
      If Args.Length < 2 Then
        ShowUsage
        Return
      End If
    
      ' Get the URI from the command line.
      Dim site As Uri = New Uri(Args(1))
    
      ' Create the request instance.
      Dim wReq as WebRequest = WebRequest.Create(site)
    
      ' Set the HTTP-specific UserAgent property.
      If TypeOf wReq Is HttpWebRequest Then
         CType(wReq, HttpWebRequest).UserAgent = _
           ".NET Framework Example Client"
      End If
    
      ' Get the response instance.
      Dim wResp As WebResponse = wReq.GetResponse()
    
      ' Read an HTTP-specific property
      If TypeOf wResp is HttpWebResponse Then
        Dim updated As DateTime = CType(wResp,HttpWebResponse).LastModified
      End If
    
      ' Get the response stream.
      Dim respStream As Stream = wResp.GetResponseStream()
    
      ' Use the Stream. This example reads the entire response with a 
      ' StreamReader into a string, and then writes the string to the 
      ' console.
      Dim reader As StreamReader = _
        New StreamReader(respStream, Encoding.ASCII)
      Dim respHTML As String = reader.ReadToEnd()
      Console.WriteLine(respHTML)
    
      ' Close the response and response stream.
      wResp.Close()
    End Sub
    
    Public Shared Sub ShowUsage
      Console.WriteLine("Attempts to GET a URI")
      Console.WriteLine(Constants.vbCrLf & "Usage")
      Console.WriteLine("  ClientGet URI")
      Console.WriteLine("Example")
      Console.WriteLIne("  ClientGet https://www.contoso.com")
    End Sub
    End Class
    

See Also

Creating Internet Requests | Handling Errors | Using Streams on the Network | Accessing the Internet Through a Proxy | Requesting Data