RestClient C# 举例 是用jsonbody ,并列出httpclient 等价的方式

以下是使用 RestSharp 发送 POST 请求并附带 JSON 请求体的示例,以及相应的使用 HttpClient 的等价方式:

首先,使用 RestSharp:

using System;
using RestSharp;
using Newtonsoft.Json;

class Program
{
    static void Main(string[] args)
    {
        // 创建 RestClient 实例
        var client = new RestClient("https://api.example.com");

        // 创建 RestRequest 实例并指定资源路径和请求方法
        var request = new RestRequest("/endpoint", Method.POST);

        // 创建一个匿名对象作为请求体,并序列化为 JSON 字符串
        var requestBody = new
        {
            Name = "John",
            Age = 30
        };
        string jsonBody = JsonConvert.SerializeObject(requestBody);

        // 设置请求体为 JSON 类型
        request.AddParameter("application/json", jsonBody, ParameterType.RequestBody);

        // 执行请求并获取响应
        IRestResponse response = client.Execute(request);

        // 检查响应是否成功
        if (response.IsSuccessful)
        {
            // 打印响应内容
            Console.WriteLine("Response content:");
            Console.WriteLine(response.Content);
        }
        else
        {
            // 打印错误信息
            Console.WriteLine($"Error: {response.ErrorMessage}");
        }
    }
}

接下来,使用 HttpClient 的等价方式:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

class Program
{
    static async Task Main(string[] args)
    {
        // 创建 HttpClient 实例
        using (HttpClient client = new HttpClient())
        {
            // 创建一个匿名对象作为请求体
            var requestBody = new
            {
                Name = "John",
                Age = 30
            };
            string jsonBody = JsonConvert.SerializeObject(requestBody);

            // 创建 StringContent 对象,指定请求体和内容类型为 JSON
            var content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            // 发送 POST 请求
            HttpResponseMessage response = await client.PostAsync("https://api.example.com/endpoint", content);

            // 检查响应是否成功
            if (response.IsSuccessStatusCode)
            {
                // 读取响应内容并打印
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine("Response content:");
                Console.WriteLine(responseBody);
            }
            else
            {
                // 打印错误信息
                Console.WriteLine($"Failed to fetch data. Status code: {response.StatusCode}");
            }
        }
    }
}

这两种方式都可以用来发送带有 JSON 请求体的 POST 请求,具体选择取决于你的项目需求和个人偏好。

posted @ 2024-05-04 08:16  摩诘  阅读(263)  评论(0编辑  收藏  举报