如何正确地向 REST 发出 GET 请求 API
How to properly issue a GET request to a REST API
我想编写一个简单的桌面应用程序,向 REST API 发出 GET 请求并将检索到的 JSON 解析为 class 个对象。
这是我主要要使用的 GET 请求:
GET /api/timesheets(Returns 时间表记录的集合)
演示响应
[
{
"activity": 174,
"project": 12,
"user": 1,
"tags": [],
"id": 5610,
"begin": "2021-05-28T01:44:00-0700",
"end": null,
"duration": null,
"description": null,
"rate": 0,
"internalRate": 0,
"exported": false,
"billable": true,
"metaFields": []
},
{
"activity": 305,
"project": 23,
"user": 1,
"tags": [
"Et quo.",
"Aut ut."
],
"id": 240,
"begin": "2021-05-25T23:33:00-0700",
"end": "2021-05-26T05:18:00-0700",
"duration": 20700,
"description": "Latitude was, or Longitude either, but thought they were mine before. If I or she should chance to be patted on the.",
"rate": 465.75,
"internalRate": 0,
"exported": false,
"billable": true,
"metaFields": []
}
]
我对用户和持续时间值最感兴趣,因为我需要将它们解析为时间表 class 对象并将它们存储在数据库中。
所以我的问题是:执行此操作的最佳实践方法是什么?
我已经尝试 Process.Start() 使用给定的 curl 并将 StandardOutput 重定向到字符串变量。这在技术上可行,但会很痛苦,我相信有更好的解决方案。
提前致谢!
您可以使用 HttpClient API 发出 REST 请求,然后直接在您的 .NET 应用程序中解析响应:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-AUTH-USER", "susan_super");
httpClient.DefaultRequestHeaders.Add("X-AUTH-TOKEN", "api_kitten");
string json = await httpClient.GetStringAsync("https://demo.kimai.org/api/timesheets?user=1");
不需要启动另一个进程来执行此操作。
How can I parse JSON with C#?
我想编写一个简单的桌面应用程序,向 REST API 发出 GET 请求并将检索到的 JSON 解析为 class 个对象。
这是我主要要使用的 GET 请求:
GET /api/timesheets(Returns 时间表记录的集合)
演示响应
[
{
"activity": 174,
"project": 12,
"user": 1,
"tags": [],
"id": 5610,
"begin": "2021-05-28T01:44:00-0700",
"end": null,
"duration": null,
"description": null,
"rate": 0,
"internalRate": 0,
"exported": false,
"billable": true,
"metaFields": []
},
{
"activity": 305,
"project": 23,
"user": 1,
"tags": [
"Et quo.",
"Aut ut."
],
"id": 240,
"begin": "2021-05-25T23:33:00-0700",
"end": "2021-05-26T05:18:00-0700",
"duration": 20700,
"description": "Latitude was, or Longitude either, but thought they were mine before. If I or she should chance to be patted on the.",
"rate": 465.75,
"internalRate": 0,
"exported": false,
"billable": true,
"metaFields": []
}
]
我对用户和持续时间值最感兴趣,因为我需要将它们解析为时间表 class 对象并将它们存储在数据库中。
所以我的问题是:执行此操作的最佳实践方法是什么?
我已经尝试 Process.Start() 使用给定的 curl 并将 StandardOutput 重定向到字符串变量。这在技术上可行,但会很痛苦,我相信有更好的解决方案。
提前致谢!
您可以使用 HttpClient API 发出 REST 请求,然后直接在您的 .NET 应用程序中解析响应:
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("X-AUTH-USER", "susan_super");
httpClient.DefaultRequestHeaders.Add("X-AUTH-TOKEN", "api_kitten");
string json = await httpClient.GetStringAsync("https://demo.kimai.org/api/timesheets?user=1");
不需要启动另一个进程来执行此操作。
How can I parse JSON with C#?