C# 使用HttpClient 发送HTTP请求

2024-01-02 15:52:10

使用HttpClient 发送请求基本实例
演示如何发送 GET 请求和 POST 请求:

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await SendGetRequest();
        await SendPostRequest();
    }

    static async Task SendGetRequest()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("https://api.example.com/data");
                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }

    static async Task SendPostRequest()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                var postData = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("key1", "value1"),
                    new KeyValuePair<string, string>("key2", "value2")
                });

                HttpResponseMessage response = await client.PostAsync("https://api.example.com/endpoint", postData);
                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

发送带参数的 请求时 可以使用UriBuilder 类来构造

using System;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        await SendGetRequestWithParams();
    }

    static async Task SendGetRequestWithParams()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                var builder = new UriBuilder("https://api.example.com/data");
                builder.Query = "param1=value1&param2=value2";

                HttpResponseMessage response = await client.GetAsync(builder.Uri);
                response.EnsureSuccessStatusCode();

                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

你可以根据需要添加或删除查询参数。然后,我们将 UriBuilder.Uri 属性传递给 HttpClient.GetAsync 方法来发送 GET 请求。在响应中,我们读取响应正文并打印到控制台上。

文章来源:https://blog.csdn.net/qq_43886548/article/details/135338581
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。