现有 接口 http://121.36.111.13:8021/getList2?pageNum=1&pageSize=10000&workOrderId=20 如何编写C#代码 响应其请求
时间: 2024-10-03 18:04:29 浏览: 38
在C#中,你可以使用HttpClient类发送HTTP GET请求来响应这个接口。首先需要添加`System.Net.Http`命名空间。以下是一个简单的示例代码:
```csharp
using System;
using System.Net.Http;
using System.Threading.Tasks;
class Program
{
private static readonly HttpClient client = new HttpClient();
static async Task Main(string[] args)
{
try
{
// 设置URL
string url = "http://121.36.111.13:8021/getList2";
// 添加查询参数
var parameters = new Dictionary<string, string>
{
{ "pageNum", "1" },
{ "pageSize", "10000" },
{ "workOrderId", "20" }
};
// 构造完整URL
url += "?" + QueryString(parameters);
// 发送GET请求并获取响应
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode(); // 检查请求是否成功
// 读取响应内容
string responseBody = await response.Content.ReadAsStringAsync();
Console.WriteLine("Response Body:\n" + responseBody);
}
catch (HttpRequestException ex)
{
Console.WriteLine($"Error occurred: {ex.Message}");
}
}
// 将字典转换为查询字符串
static string QueryString(Dictionary<string, string> dictionary)
{
StringBuilder sb = new StringBuilder();
foreach (var item in dictionary)
{
sb.AppendFormat("{0}={1}&", item.Key, WebUtility.UrlEncode(item.Value));
}
return sb.Length > 0 ? sb.ToString(0, sb.Length - 1) : ""; // 移除末尾"&"
}
}
```
这段代码会向指定的URL发送GET请求,并附带给定的查询参数。如果请求成功,它将打印出服务器返回的响应体。
阅读全文