Microsoft Learn

HttpWebResponse Class

Namespace: System.Net
Assembly: System (in System.dll)

Summary

Represents a response from an HTTP request.

Syntax

public class HttpWebResponse : WebResponse, IDisposable { ... }

Namespace: System.Net
Assembly: System (in System.dll)

Remarks

The HttpWebResponse class is returned by the HttpClient.GetResponse method when you send an HTTP request.

This class provides access to the response headers, status code, and the response stream.

It is important to close the response stream when you are finished with it to release resources.

Properties

Name Description
CharacterSet Gets the character set of the response stream.
ContentLength Gets the length of the content in the response stream.
ContentType Gets the MIME type of the response.
Cookies Gets or sets the cookies associated with the response.
Headers Gets a WebHeaderCollection object that contains the HTTP headers for the response.
Method Gets the HTTP method used to execute the request.
ProtocolVersion Gets the version of the HTTP protocol used by the server.
ResponseUri Gets the Uniform Resource Identifier (URI) of the server that sent the response.
StatusCode Gets an HttpStatusCode value that indicates the status of the response.
StatusDescription Gets a string describing the status of the response.

Methods

Name Description
Close Closes the response stream and releases resources.
GetResponseStream Returns a stream that contains the response body from the server.

Example

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

public class Example
{
    public static void Main(string[] args)
    {
        string url = "https://www.example.com";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";

        try
        {
            using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
            {
                Console.WriteLine($"Status Code: {response.StatusCode}");
                Console.WriteLine($"Content Type: {response.ContentType}");

                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    string responseBody = reader.ReadToEnd();
                    Console.WriteLine($"Response Body (first 100 chars): {responseBody.Substring(0, Math.Min(responseBody.Length, 100))}");
                }
            }
        }
        catch (WebException e)
        {
            Console.WriteLine($"An error occurred: {e.Message}");
        }
    }
}