RestClient C# 举例 是用jsonbody ,并列出httpclient 等价的方式
生活随笔
收集整理的這篇文章主要介紹了
RestClient C# 举例 是用jsonbody ,并列出httpclient 等价的方式
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
以下是使用 RestSharp 發(fā)送 POST 請求并附帶 JSON 請求體的示例,以及相應的使用 HttpClient 的等價方式:
首先,使用 RestSharp:
using System;
using RestSharp;
using Newtonsoft.Json; class Program
{
static void Main(string[] args)
{
// 創(chuàng)建 RestClient 實例
var client = new RestClient("https://api.example.com"); // 創(chuàng)建 RestRequest 實例并指定資源路徑和請求方法
var request = new RestRequest("/endpoint", Method.POST); // 創(chuàng)建一個匿名對象作為請求體,并序列化為 JSON 字符串
var requestBody = new
{
Name = "John",
Age = 30
};
string jsonBody = JsonConvert.SerializeObject(requestBody); // 設置請求體為 JSON 類型
request.AddParameter("application/json", jsonBody, ParameterType.RequestBody); // 執(zhí)行請求并獲取響應
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)
{
// 創(chuàng)建 HttpClient 實例
using (HttpClient client = new HttpClient())
{
// 創(chuàng)建一個匿名對象作為請求體
var requestBody = new
{
Name = "John",
Age = 30
};
string jsonBody = JsonConvert.SerializeObject(requestBody); // 創(chuàng)建 StringContent 對象,指定請求體和內容類型為 JSON
var content = new StringContent(jsonBody, Encoding.UTF8, "application/json"); // 發(fā)送 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}");
}
}
}
}
這兩種方式都可以用來發(fā)送帶有 JSON 請求體的 POST 請求,具體選擇取決于你的項目需求和個人偏好。
總結
以上是生活随笔為你收集整理的RestClient C# 举例 是用jsonbody ,并列出httpclient 等价的方式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 进化吧!我的C++!!
- 下一篇: 使用Session防止表单重复提交