How does one use HttpClient in C#?
The C# HttpClient is a class used for performing HTTP communication, it is defined in the System.Net.Http namespace. The HttpClient class offers a set of methods and properties for sending HTTP requests and receiving HTTP responses.
Here are some common usages of the HttpClient class:
- Instantiate a HttpClient object.
HttpClient client = new HttpClient();
- Send a GET request.
string url = "http://example.com/api";
HttpResponseMessage response = await client.GetAsync(url);
- Send a POST request.
string url = "http://example.com/api";
HttpContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(url, content);
- Add a request header:
client.DefaultRequestHeaders.Add("Authorization", "Bearer token");
- Receive response.
string responseBody = await response.Content.ReadAsStringAsync();
- Error handling:
if (!response.IsSuccessStatusCode)
{
// 处理错误
}
- Close the HttpClient object.
client.Dispose();
This is just some basic usage of HttpClient, there are many other ways to use it, such as sending PUT, DELETE requests, setting timeout, handling redirections, etc. You can further study and utilize the HttpClient class based on your specific needs.