-
Notifications
You must be signed in to change notification settings - Fork 5
HttpClient
HttpClient is a powerful and flexible HTTP client library for .NET, used to send HTTP requests and receive HTTP responses from web resources.
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; }
}
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.
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.
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.
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.
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.
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.
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.
-
Introduction to C#
What is C#? -
Variables and Data Types
Understand how to declare and use variables. -
Operators
Arithmetic, relational, and logical operators in C#. -
Control Statements
If-else, switch, and looping constructs.
-
Classes and Objects
Basics of OOP in C#. -
Inheritance
How to use inheritance effectively. -
Polymorphism
Method overriding and overloading. -
Encapsulation
Understanding access modifiers.
-
LINQ Basics
Working with Language Integrated Query. -
Asynchronous Programming
Introduction to async/await. -
File Handling
Reading and writing files.
-
Number Formatting
Formatting numbers in C#. -
Exception Handling
Handling runtime errors effectively. -
Working with Dates
DateTime and time zone handling. -
Using Keyword in C#
Different usages of theusing
keyword in C#.
-
Setting Up Development Environment
Installing Visual Studio and .NET SDK. - Useful Libraries Libraries and tools for C# development.