Http Namespace
Provides types for sending and receiving HTTP requests and responses. This namespace is fundamental for building web clients and services in .NET.
Classes
HttpClient (Class)
Sends an HTTP request, or gets an HTTP response message, as an asynchronous operation.
HttpClientHandler (Class)Provides a basic implementation of the HttpMessageHandler
that sends HTTP requests.
Represents an HTTP entity body and the Content-Type header.
HttpResponseMessage (Class)Represents an HTTP response message.
HttpRequestMessage (Class)Represents an HTTP request message.
HttpLoginResponse (Class)Represents a response to an HTTP login request.
HttpRequestHeader (Enum)Specifies the header fields for an HTTP request.
HttpResponseHeader (Enum)Specifies the header fields for an HTTP response.
Class Details
HttpClient
Sends an HTTP request, or gets an HTTP response message, as an asynchronous operation.
public class HttpClient : IDisposable
Constructors
Methods
GetAsync(Uri)
GetAsync(String)
PostAsync(Uri, HttpContent)
PostAsync(String, HttpContent)
PutAsync(Uri, HttpContent)
DeleteAsync(Uri)
SendAsync(HttpRequestMessage)
Dispose()
HttpClientHandler
Provides a basic implementation of the
HttpMessageHandler
that sends HTTP requests.
public class HttpClientHandler : HttpMessageHandler
Properties
Methods
HttpContent
Represents an HTTP entity body and the Content-Type header. This is an abstract class.
public abstract class HttpContent : IDisposable
Methods
HttpResponseMessage
Represents an HTTP response message.
public class HttpResponseMessage : IDisposable
Properties
Version (Version)
StatusCode (HttpStatusCode)
ReasonPhrase (String)
Content (HttpContent)
RequestMessage (HttpRequestMessage)
IsSuccessStatusCode (Boolean)
Methods
HttpRequestMessage
Represents an HTTP request message.
public class HttpRequestMessage : IDisposable
Properties
Method (HttpMethod)
RequestUri (Uri)
Version (Version)
Content (HttpContent)
Headers (HttpRequestHeaders)
Methods
HttpLoginResponse
Represents a response to an HTTP login request.
public class HttpLoginResponse
Properties
Example Usage
Here's a simple example of how to make a GET request using HttpClient
:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync("https://www.example.com");
response.EnsureSuccessStatusCode(); // Throw an exception if the status code is not success
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
catch (HttpRequestException e)
{
Console.WriteLine($"Request error: {e.Message}");
}
}
}
}