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

C# POST 请求传递 Json 参数 (application/x-www-form-urlencoded)

原文地址: https://www.cveoy.top/t/topic/pJEh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录