C# POST applicationx-www-form-urlencoded 请求 Json参数如何传递
要在C#中使用POST请求传递Json参数,需要使用HttpClient类。以下是一个示例代码,展示了如何发送POST请求并传递Json参数:
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
class Program
{
static async Task Main(string[] args)
{
using (HttpClient client = new HttpClient())
{
// 设置请求的内容类型为 application/x-www-form-urlencoded
client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/x-www-form-urlencoded");
// 构造要发送的Json参数
string jsonParams = "{\"name\":\"John Doe\",\"age\":30}";
// 将Json参数编码为 application/x-www-form-urlencoded 格式
var formContent = new FormUrlEncodedContent(new[]
{
new KeyValuePair<string, string>("json", jsonParams)
});
// 发送POST请求
var response = await client.PostAsync("https://example.com/api/endpoint", formContent);
// 读取响应内容
var responseContent = await response.Content.ReadAsStringAsync();
// 输出响应内容
Console.WriteLine(responseContent);
}
}
}
在上述代码中,我们首先创建了一个HttpClient对象,并设置了请求的内容类型为application/x-www-form-urlencoded。然后,我们构造了要发送的Json参数,并将其编码为application/x-www-form-urlencoded格式。接下来,我们使用PostAsync方法发送POST请求,并读取响应内容。
请注意,在这个示例中,我们将Json参数的键设置为json,你可以根据实际情况更改它。另外,你还需要将https://example.com/api/endpoint替换为实际的API端点URL
原文地址: https://www.cveoy.top/t/topic/h0zF 著作权归作者所有。请勿转载和采集!