Skip to content

HttpClient

Sann Lynn Htun edited this page Nov 22, 2024 · 2 revisions

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

private async Task Read()
{
    using HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync("https://jsonplaceholder.typicode.com/posts");
    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        List<BlogModel> posts = JsonConvert.DeserializeObject<List<BlogModel>>(json);
        foreach (var post in posts)
        {
            Console.WriteLine(post.Id);
            Console.WriteLine(post.Title);
            Console.WriteLine(post.Body);
            Console.WriteLine("----------------------------");
        }
    }
    else
    {
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

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

public async Task Edit(int id)
{
    string url = $"https://jsonplaceholder.typicode.com/posts/{id}";
    using HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.GetAsync(url);
    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        BlogModel post = JsonConvert.DeserializeObject<BlogModel>(json);
        Console.WriteLine(post.Id);
        Console.WriteLine(post.Title);
        Console.WriteLine(post.Body);
    }
    else
    {
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

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

public async Task Create(string title, string body, int userId)
{
    BlogModel post = new BlogModel
    {
        Title = title,
        Body = body,
        UserId = userId
    };
    string jsonPost = JsonConvert.SerializeObject(post);
    HttpContent httpContent = new StringContent(jsonPost, Encoding.UTF8, "application/json");

    using HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PostAsync("https://jsonplaceholder.typicode.com/posts", httpContent);
    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
    else
    {
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

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

public async Task Update(int id, string title, string body, int userId)
{
    BlogModel post = new BlogModel
    {
        Id = id,
        Title = title,
        Body = body,
        UserId = userId
    };
    string jsonPost = JsonConvert.SerializeObject(post);
    HttpContent httpContent = new StringContent(jsonPost, Encoding.UTF8, "application/json");

    string url = $"https://jsonplaceholder.typicode.com/posts/{id}";
    using HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.PutAsync(url, httpContent);
    if (response.IsSuccessStatusCode)
    {
        string json = await response.Content.ReadAsStringAsync();
        Console.WriteLine(json);
    }
    else
    {
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

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

private async Task Delete(int id)
{
    string url = $"https://jsonplaceholder.typicode.com/posts/{id}";
    using HttpClient client = new HttpClient();
    HttpResponseMessage response = await client.DeleteAsync(url);
    if (response.IsSuccessStatusCode)
    {
        Console.WriteLine("Deleted successfully.");
    }
    else
    {
        Console.WriteLine(await response.Content.ReadAsStringAsync());
    }
}

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.

C# Basics Wiki

Core Concepts

Object-Oriented Programming (OOP)

Advanced Topics

Miscellaneous

Tools and Resources

Clone this wiki locally