System.Net.Http Namespace
This namespace provides classes for sending HTTP requests and receiving HTTP responses.
Summary
The System.Net.Http namespace is fundamental for building applications that communicate over the web using the HTTP protocol. It offers a high-level abstraction for managing HTTP requests and responses, making it easier to interact with web services and APIs.
Key components include:
HttpClient: The primary class for sending HTTP requests. It manages connections and offers methods for common HTTP verbs (GET, POST, PUT, DELETE, etc.).HttpRequestMessage: Represents an HTTP request.HttpResponseMessage: Represents an HTTP response.HttpContent: Represents the body of an HTTP request or response. Various derived classes exist for different content types (strings, byte arrays, streams).
Key Classes
HttpClient
The HttpClient class is the main entry point for making HTTP requests. It's designed to be instantiated once and reused throughout the application's lifetime for efficiency.
public class HttpClient : IDisposableCommon Usage:
using System.Net.Http;
using System.Threading.Tasks;
public class ApiClient
{
private static readonly HttpClient client = new HttpClient();
public async Task<string> GetApiDataAsync(string url)
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // Throws if the status code is not 2xx
string responseBody = await response.Content.ReadAsStringAsync();
return responseBody;
}
}
HttpRequestMessage
Represents an HTTP request message. You typically create an HttpRequestMessage to specify details like the HTTP method, URI, headers, and content of a request.
public class HttpRequestMessageHttpResponseMessage
Represents an HTTP response message received from an HTTP server. It contains the status code, headers, and content of the response.
public class HttpResponseMessageHttpContent
An abstract base class that represents the HTTP content associated with a request or response. It provides methods for serializing the content to a stream and for determining the content type.
public abstract class HttpContent : IDisposableDerived Classes of HttpContent
StringContent: For text-based content.StreamContent: For streaming content.ByteArrayContent: For content represented as a byte array.MultipartFormDataContent: For sending forms with files.
Common Operations
Sending GET Requests
Use the HttpClient.GetAsync() method.
var response = await httpClient.GetAsync("https://api.example.com/data");
response.EnsureSuccessStatusCode();
var data = await response.Content.ReadAsStringAsync();
Sending POST Requests
Create a StringContent (or other HttpContent derived class) and use HttpClient.PostAsync().
var requestData = new { Name = "Example", Value = 123 };
var content = new StringContent(JsonSerializer.Serialize(requestData), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync("https://api.example.com/create", content);
response.EnsureSuccessStatusCode();
Handling Responses
Check the StatusCode property and read the Content.
if (response.IsSuccessStatusCode)
{
var responseString = await response.Content.ReadAsStringAsync();
// Process the response
}
else
{
// Handle error
}
API Reference
Explore the detailed API documentation for classes and methods within the System.Net.Http namespace:
| Class/Method | Description |
|---|---|
HttpClient |
Provides methods for sending HTTP requests and receiving HTTP responses from a resource identified by a URI. |
HttpClient.GetAsync(string requestUri) |
Sends a GET request to the specified Uri as an asynchronous operation. |
HttpClient.PostAsync(string requestUri, HttpContent content) |
Sends a POST request to the specified Uri as an asynchronous operation. |
HttpRequestMessage |
Represents an HTTP message. |
HttpResponseMessage |
Represents a message that is sent to an HTTP server as the result of aarschijnlijk request. |
HttpContent |
Represents the HTTP content associated with an HTTP request or response. |
StringContent |
Represents an HTTP entity body that contains characters. |
MultipartFormDataContent |
Represents a set of form-urlencoded data as a set of key/value pairs. |