Click to Rate and Give Feedback
MSDN
MSDN Library
Visual Studio 2008
Visual Studio
Network Programming
Requesting Data
 How to: Request Data Using the WebR...
Collapse All/Expand All Collapse All
This page is specific to
Microsoft Visual Studio 2008/.NET Framework 3.5

Other versions are also available for the following:
.NET Framework Developer's Guide
How to: Request Data Using the WebRequest Class

The following procedure describes the steps used to request a resource from a server, for example, a Web page or file. The resource must be identified by a URI.

To request data from a host server

  1. Create a WebRequest instance by calling Create with the URI of the resource.

    C#
    WebRequest request = WebRequest.Create("http://www.contoso.com/");

    Visual Basic
    Dim request as WebRequest = WebRequest.Create("http://www.contoso.com/")
    
    NoteNote:

    The .NET Framework provides protocol-specific classes derived from WebRequest and WebResponse for URIs that begin with "http:", "https:'', "ftp:", and "file:". To access resources using other protocols, you must implement protocol-specific classes that derive from WebRequest and WebResponse. For more information, see Programming Pluggable Protocols .

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

    C#
    request.Credentials = CredentialCache.DefaultCredentials;

    Visual Basic
    request.Credentials = CredentialCache.DefaultCredentials

    In most cases, the WebRequest class is sufficient to receive data. However, if you need to set protocol-specific properties, you must cast the WebRequest to the protocol-specific type. For example, to access the HTTP-specific properties of HttpWebRequest, cast the WebRequest to an HttpWebRequest reference. The following code example shows how to set the HTTP-specific UserAgent property.

    C#
    ((HttpWebRequest)request).UserAgent = ".NET Framework Example Client";

    Visual Basic
    Ctype(request,HttpWebRequest).UserAgent = ".NET Framework Example Client"
    
  3. To send the request to the server, call GetResponse. The actual type of the returned WebResponse object is determined by the scheme of the requested URI.

    C#
    WebResponse response = request.GetResponse();

    Visual Basic
    Dim response As WebResponse = request.GetResponse()
    
    NoteNote:

    After you are finished with a WebResponse object, you must close it by calling the Close method. Alternatively, if you have gotten the response stream from the response object, you can close the stream by calling the Stream..::.Close method. If you do not close either the response or the stream, your application can run out of connections to the server and become unable to process additional requests.

  4. You can access the properties of the WebResponse or cast the WebResponse to a protocol-specific instance to read protocol-specific properties. For example, to access the HTTP-specific properties of HttpWebResponse, cast the WebResponse to a HttpWebResponse reference. The following code example shows how to display the status information sent with a response.

    C#
    Console.WriteLine (((HttpWebResponse)response).StatusDescription);

    Visual Basic
    Console.WriteLine(CType(response,HttpWebResponse).StatusDescription)
  5. To get the stream containing response data sent by the server, use the GetResponseStream method of the WebResponse.

    C#
    Stream dataStream = response.GetResponseStream ();

    Visual Basic
    Dim dataStream As Stream = response.GetResponseStream()
    
  6. After reading the data from the response, you must either close the response stream using the Stream.Close method or close the response using the WebResponse.Close method. 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.

    C#
    response.Close();

    Visual Basic
    response.Close()
    
C#
using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // Create a request for the URL. 
            WebRequest request = WebRequest.Create (
              "http://www.contoso.com/default.html");
            // If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials;
            // Get the response.
            WebResponse response = request.GetResponse ();
            // Display the status.
            Console.WriteLine (((HttpWebResponse)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);
            // Clean up the streams and the response.
            reader.Close ();
            response.Close ();
        }
    }
}
Visual Basic
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
Namespace Examples.System.Net
    Public Class WebRequestGetExample

        Public Shared Sub Main()
            ' Create a request for the URL. 
            Dim request As WebRequest = _
              WebRequest.Create("http://www.contoso.com/default.html")
            ' If required by the server, set the credentials.
            request.Credentials = CredentialCache.DefaultCredentials
            ' Get the response.
            Dim response As WebResponse = request.GetResponse()
            ' Display the status.
            Console.WriteLine(CType(response,HttpWebResponse).StatusDescription)
            ' Get the stream containing content returned by the server.
            Dim dataStream As Stream = response.GetResponseStream()
            ' Open the stream using a StreamReader for easy access.
            Dim reader As New StreamReader(dataStream)
            ' Read the content.
            Dim responseFromServer As String = reader.ReadToEnd()
            ' Display the content.
            Console.WriteLine(responseFromServer)
            ' Clean up the streams and the response.
            reader.Close()
            response.Close()
        End Sub 
    End Class 
End Namespace
Tags What's this?: Add a tag
Community Content   What is Community Content?
Add new content RSS  Annotations
Processing
© 2009 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks | Privacy Statement
Page view tracker