HttpClient

HttpClient

HttpClient is a powerful and flexible HTTP client library for .NET, used to send HTTP requests and receive HTTP responses from web resources.

BlogModel Class

Description

The BlogModel class maps the JSON structure used by the JSONPlaceholder API for blog posts.

public class BlogModel
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Body { get; set; }
    public int UserId { get; set; }
}

HttpClient Example with JSONPlaceholder

Description

The HttpClientExample class demonstrates how to use the HttpClient class in C# to interact with the JSONPlaceholder API. This class includes methods to perform the basic CRUD operations (Create, Read, Update, Delete) against the fake API endpoints.

Run Method

public async Task Run()
{
    await Read();
    await Edit(1);
    await Edit(100);
    await Create("title", "body", 1);
    await Update(1, "updated title", "updated body", 1);
    await Delete(1);
}

Summary: This method serves as an entry point to test various API operations. Uncomment the desired operation to execute it.

Read Method

Summary: This method sends a GET request to the JSONPlaceholder API to retrieve all posts and prints each post's data to the console.

Edit Method

Summary: This method sends a GET request to retrieve a specific post based on the provided id and prints the details if found.

Create Method

Summary: This method sends a POST request to create a new post with the provided title, body, and userId. It prints the response from the API.

Update Method

Summary: This method sends a PUT request to update an existing post based on the provided id, title, body, and userId. It prints the response from the API.

Delete Method

Summary: This method sends a DELETE request to remove a post from the API based on the provided id. It prints the response from the API.

Each method in the HttpClientExample class demonstrates how to interact with the JSONPlaceholder API using HttpClient. The class covers basic CRUD operations and ensures asynchronous operations are handled properly.