c# 写一段程序 向post接口 http://121.36.111.13:8021/otherRoute/getWorkerList 发送json
时间: 2024-10-07 14:02:48 浏览: 27
C# Http(Get/Post)以及Json解析源码
在C#中,你可以使用HttpClient库来发送POST请求并携带JSON数据。以下是一个简单的示例:
```csharp
using System;
using System.Net.Http;
using System.Text.Json;
class Program
{
static async Task Main(string[] args)
{
string apiUrl = "http://121.36.111.13:8021/otherRoute/getWorkerList";
string jsonContent = "{\"key\":\"value\"}"; // 替换为你实际需要的JSON数据
try
{
HttpClient client = new HttpClient();
HttpContent content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
HttpResponseMessage response = await client.PostAsync(apiUrl, content);
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Request successful. Response status code: {response.StatusCode}");
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response body:");
Console.WriteLine(responseBody);
}
else
{
Console.WriteLine($"Request failed with status code: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
}
```
在这个例子中,我们首先创建了一个HttpClient实例,然后设置HTTP请求的内容为JSON字符串,并指定其MIME类型为`application/json`。接着,我们使用PostAsync方法发送POST请求到指定的URL。如果请求成功,我们会读取响应内容并打印出来。
阅读全文