HttpClient in C#: Complete Guide
To send HTTP requests using the HttpClient class in C#, you need to follow these steps:
- Instantiate a HttpClient.
HttpClient client = new HttpClient();
- Provide the basic information needed for the request, such as the URL, request method, and request headers.
client.BaseAddress = new Uri("http://example.com/api/");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
- Send an HTTP request and receive a response.
HttpResponseMessage response = await client.GetAsync("endpoint");
string responseBody = await response.Content.ReadAsStringAsync();
- Deal with the response.
if (response.IsSuccessStatusCode)
{
// 处理成功的情况
}
else
{
// 处理失败的情况
}
- Finally, you need to release the HttpClient instance.
client.Dispose();
The above are the basic methods for sending HTTP requests using the HttpClient class, which can be further customized for specific requirements by adjusting parameters and handling errors.