Represents an HTTP response message.
System.Net.Http
The HttpResponseContent class is a fundamental part of handling HTTP responses in .NET. It encapsulates the data received from an HTTP server as a response to a request. This includes status codes, headers, and the actual content of the response body.
It provides methods to access and manage the response content, such as reading it as a string, as a byte stream, or disposing of the resources associated with the response.
HttpResponseContent class.
Here's a basic example of how to use HttpResponseContent to make an HTTP request and process the response:
using System;
using System.Net.Http;
using System.Threading.Tasks;
public class Example
{
public static async Task GetApiDataAsync(string url)
{
using (HttpClient client = new HttpClient())
{
try
{
HttpResponseMessage response = await client.GetAsync(url);
// Ensure the request was successful
response.EnsureSuccessStatusCode();
// Access the content and read it as a string
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine($"Response Body:\n{responseBody}");
// Access headers
Console.WriteLine("\nResponse Headers:");
foreach (var header in response.Headers)
{
Console.WriteLine($"{header.Key}: {string.Join(", ", header.Value)}");
}
}
catch (HttpRequestException e)
{
Console.WriteLine($"\nException Caught:\n {e.Message}");
}
}
}
public static async Task Main(string[] args)
{
await GetApiDataAsync("https://jsonplaceholder.typicode.com/posts/1");
}
}