HttpRequestMessage Class
Namespace: System.Net.Http
Represents an HTTP request message.
The HttpRequestMessage class represents an HTTP request message. It is used to send HTTP requests to a server and includes properties for the request method, URI, headers, and content.
Constructors
-
HttpRequestMessage()
Initializes a new instance of the
HttpRequestMessageclass. -
HttpRequestMessage(HttpMethod method, string requestUri)
Initializes a new instance of the
HttpRequestMessageclass with the specified HTTP method and request URI.Parameters:method: The HTTP method of the request.requestUri: The URI of the request.
-
HttpRequestMessage(HttpMethod method, Uri requestUri)
Initializes a new instance of the
HttpRequestMessageclass with the specified HTTP method and request URI.Parameters:method: The HTTP method of the request.requestUri: The URI of the request.
Properties
-
Content
Gets or sets the HTTP content for the request.
HttpContent Content { get; set; } -
Headers
Gets the collection of HTTP request headers.
HttpHeaders Headers { get; } -
Method
Gets or sets the HTTP method for the request.
HttpMethod Method { get; set; } -
Options
Gets a collection of HTTP request options.
HttpRequestOptions Options { get; } -
Properties
Gets the collection of HTTP request properties.
ICollection<KeyValuePair<string, object>> Properties { get; } -
RequestUri
Gets or sets the URI of the HTTP request.
Uri RequestUri { get; set; } -
Version
Gets or sets the HTTP protocol version for the request.
Version Version { get; set; }
Methods
-
Dispose()
Releases the unmanaged resources that are used by the HTTP message and optionally releases the managed resources.
-
Dispose(bool disposing)
Releases the unmanaged resources that are used by the HTTP message and optionally releases the managed resources.
Examples
Here's a basic example of how to create and use an HttpRequestMessage:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task MakeRequest()
{
using (var request = new HttpRequestMessage(HttpMethod.Get, "https://www.example.com/api/data"))
{
// Add custom headers if needed
request.Headers.Add("Accept", "application/json");
// Optionally add content for POST, PUT, etc.
// request.Content = new StringContent("{\"key\": \"value\"}", System.Text.Encoding.UTF8, "application/json");
using (var client = new HttpClient())
{
HttpResponseMessage response = await client.SendAsync(request);
response.EnsureSuccessStatusCode(); // Throws an exception if the status code is not success
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine(responseBody);
}
}
}
}