How to: Send data by using the WebRequest class

The following procedure describes the steps to send data to a server. This procedure is commonly used to post data to a Web page.

To send data to a host server

  1. Create a WebRequest instance by calling WebRequest.Create with the URI of a resource, such as a script or ASP.NET page, that accepts data. For example:

    WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx");  
    
    Dim request as WebRequest = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx")  
    

    Note

    The .NET Framework provides protocol-specific classes derived from the WebRequest and WebResponse classes for URIs that begin with http:, https:, ftp:, and file:. If you need to set or read protocol-specific properties, you must cast your WebRequest or WebResponse object to a protocol-specific object type. For more information, see Programming pluggable protocols.

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

    request.Credentials = CredentialCache.DefaultCredentials;  
    
    request.Credentials = CredentialCache.DefaultCredentials  
    
  3. Specify a protocol method that permits data to be sent with a request, such as the HTTP POST method:

    request.Method = "POST";  
    
    request.Method = "POST"  
    
  4. Set the ContentLength property to the number of bytes you're including with your request. For example:

    request.ContentLength = byteArray.Length;  
    
    request.ContentLength = byteArray.Length  
    
  5. Set the ContentType property to an appropriate value. For example:

    request.ContentType = "application/x-www-form-urlencoded";  
    
    request.ContentType = "application/x-www-form-urlencoded"  
    
  6. Get the stream that holds request data by calling the GetRequestStream method. For example:

    Stream dataStream = request.GetRequestStream();  
    
    Dim dataStream As Stream = request.GetRequestStream()  
    
  7. Write the data to the Stream object returned by the GetRequestStream method. For example:

    dataStream.Write(byteArray, 0, byteArray.Length);  
    
    dataStream.Write(byteArray, 0, byteArray.Length)  
    
  8. Close the request stream by calling the Stream.Close method. For example:

    dataStream.Close();  
    
    dataStream.Close()  
    
  9. Send the request to the server by calling WebRequest.GetResponse. This method returns an object containing the server's response. The returned WebResponse object's type is determined by the scheme of the request's URI. For example:

    WebResponse response = request.GetResponse();  
    
    Dim response As WebResponse = request.GetResponse()  
    
  10. You can access the properties of your WebResponse object or cast it to a protocol-specific instance to read protocol-specific properties.

    For example, to access the HTTP-specific properties of HttpWebResponse, cast your WebResponse object to an HttpWebResponse reference. The following code example shows how to display the HTTP-specific HttpWebResponse.StatusDescription property sent with a response:

    Console.WriteLine(((HttpWebResponse)response).StatusDescription);    
    
    Console.WriteLine(CType(response, HttpWebResponse).StatusDescription)  
    
  11. To get the stream containing response data sent by the server, call the WebResponse.GetResponseStream method of your WebResponse object. For example:

    Stream dataStream = response.GetResponseStream();  
    
    Dim dataStream As Stream = response.GetResponseStream()  
    
  12. After you've read the data from the response object, either close it with the WebResponse.Close method or close the response stream with the Stream.Close method. If you don't close either the response or the stream, your application can run out of server connections and become unable to process additional requests. Because the WebResponse.Close method calls Stream.Close when it closes the response, it's not necessary to call Close on both the response and stream objects, although doing so isn't harmful. For example:

    response.Close();  
    
    response.Close()  
    

Example

The following example shows how to send data to a web server and read the data in its response:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestPostExample
    {
        public static void Main()
        {
            // Create a request using a URL that can receive a post.   
            WebRequest request = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ");
            // Set the Method property of the request to POST.  
            request.Method = "POST";
            
            // Create POST data and convert it to a byte array.  
            string postData = "This is a test that posts this string to a Web server.";
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);
            
            // Set the ContentType property of the WebRequest.  
            request.ContentType = "application/x-www-form-urlencoded";
            // Set the ContentLength property of the WebRequest.  
            request.ContentLength = byteArray.Length;
            
            // Get the request stream.  
            Stream dataStream = request.GetRequestStream();
            // Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length);
            // Close the Stream object.  
            dataStream.Close();
            
            // Get the response.  
            WebResponse response = request.GetResponse();
            // Display the status.  
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);
            
            // Get the stream containing content returned by the server.  
            // The using block ensures the stream is automatically closed.
            using (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);
            }
            
            // Close the response.  
            response.Close();
        }
    }
}
Imports System.IO
Imports System.Net
Imports System.Text

Namespace Examples.System.Net
    Public Class WebRequestPostExample
        Public Shared Sub Main()
            ' Create a request using a URL that can receive a post.   
            Dim request As WebRequest = WebRequest.Create("http://www.contoso.com/PostAccepter.aspx ")
            ' Set the Method property of the request to POST.  
            request.Method = "POST"

            ' Create POST data and convert it to a byte array.  
            Dim postData As String = "This is a test that posts this string to a Web server."
            Dim byteArray As Byte() = Encoding.UTF8.GetBytes(postData)

            ' Set the ContentType property of the WebRequest.  
            request.ContentType = "application/x-www-form-urlencoded"
            ' Set the ContentLength property of the WebRequest.  
            request.ContentLength = byteArray.Length

            ' Get the request stream.  
            Dim dataStream As Stream = request.GetRequestStream()
            ' Write the data to the request stream.  
            dataStream.Write(byteArray, 0, byteArray.Length)
            ' Close the Stream object.  
            dataStream.Close()

            ' 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.  
            ' The using block ensures the stream is automatically closed.
            Using dataStream1 As Stream = response.GetResponseStream()
                ' Open the stream using a StreamReader for easy access.  
                Dim reader As New StreamReader(dataStream1)
                ' Read the content.  
                Dim responseFromServer As String = reader.ReadToEnd()
                ' Display the content.  
                Console.WriteLine(responseFromServer)
            End Using

            ' Clean up the response.  
            response.Close()
        End Sub
    End Class
End Namespace

See also