HttpResponse Class

Namespace: System.Net.Http

Represents a Hypertext Transfer Protocol (HTTP) response message received from an HTTP server.

Syntax

public sealed class HttpResponse : IDisposable

Remarks

The HttpResponse class provides a convenient way to access the properties of an HTTP response, such as the status code, headers, and content. It is typically obtained as the result of an HTTP request made using classes like HttpClient.

The HttpResponse object implements IDisposable, and it's important to dispose of it when you are finished with it to release any unmanaged resources it may hold.

Constructors

There are no public constructors for the HttpResponse class. Instances are created by the HttpClient class.

Properties

Methods

Example

using System;
using System.Net.Http;
using System.Threading.Tasks;

public class Example
{
    public static async Task GetHttpResponseAsync(string url)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode(); // Throws if status code is not 2xx

                Console.WriteLine($"Status Code: {response.StatusCode}");
                Console.WriteLine($"Content-Type: {response.Content.Headers.ContentType?.MediaType}");

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response Body Length: {responseBody.Length}");
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }

    public static async Task Main(string[] args)
    {
        await GetHttpResponseAsync("https://www.example.com");
    }
}

See Also