在 C# 中,你可以使用多种方法从 HTTP 接口获取 JSON 数据。以下是几种常见的方法,包括使用 HttpClient
和 WebClient
。这里我们主要使用 HttpClient
,因为它提供了更多的功能和更好的性能。接口请替换使用对应的您需要访问的url。
使用 HttpClient
HttpClient
是 .NET 中用于发送 HTTP 请求和接收 HTTP 响应的推荐类。以下是一个示例,展示如何从指定的 URL 获取 JSON 数据并解析它。
1. 安装必要的 NuGet 包
确保你已经安装了 System.Net.Http
和 Newtonsoft.Json
(如果需要解析 JSON)。
Shell
深色版本
Install-Package System.Net.Http
Install-Package Newtonsoft.Json
2. 编写代码
Csharp
深色版本
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
class Program
{
static async Task Main(string[] args)
{
string url = "http://a.mairui.club/hsrl/ssjy";
using (HttpClient client = new HttpClient())
{
try
{
// 发送 GET 请求
HttpResponseMessage response = await client.GetAsync(url);
// 确保请求成功
if (response.IsSuccessStatusCode)
{
// 读取响应内容
string jsonContent = await response.Content.ReadAsStringAsync();
// 解析 JSON
JObject jsonObject = JObject.Parse(jsonContent);
// 打印 JSON 内容
Console.WriteLine(jsonObject.ToString());
}
else
{
Console.WriteLine($"请求失败,状态码: {response.StatusCode}");
}
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
}
}
详细说明
-
创建
HttpClient
实例:HttpClient
是一个可重用的对象,建议在整个应用程序生命周期中只创建一次实例。在这里,我们使用using
语句来确保资源被正确释放。
-
发送 GET 请求:
client.GetAsync(url)
发送一个异步的 GET 请求到指定的 URL,并返回一个HttpResponseMessage
对象。
-
检查响应状态码:
response.IsSuccessStatusCode
检查响应是否成功(状态码在 200-299 之间)。
-
读取响应内容:
response.Content.ReadAsStringAsync()
读取响应的内容并将其作为字符串返回。
-
解析 JSON:
- 使用
Newtonsoft.Json
库中的JObject.Parse
方法将 JSON 字符串解析为JObject
对象。
- 使用
-
打印 JSON 内容:
- 将解析后的 JSON 对象转换为字符串并打印出来。
使用 WebClient
(不推荐)
虽然 WebClient
也可以用来获取数据,但它在 .NET Core 和 .NET 5+ 中已经被标记为过时,因此不推荐使用。如果你仍然想了解如何使用 WebClient
,可以参考以下示例:
Csharp
深色版本
using System;
using System.Net;
using Newtonsoft.Json.Linq;
class Program
{
static void Main(string[] args)
{
string url = "http://a.mairui.club/hsrl/";
using (WebClient client = new WebClient())
{
try
{
// 下载数据
string jsonContent = client.DownloadString(url);
// 解析 JSON
JObject jsonObject = JObject.Parse(jsonContent);
// 打印 JSON 内容
Console.WriteLine(jsonObject.ToString());
}
catch (WebException ex)
{
Console.WriteLine($"网络错误: {ex.Message}");
}
catch (Exception ex)
{
Console.WriteLine($"发生错误: {ex.Message}");
}
}
}
}
总结
HttpClient
:推荐使用,提供了更多的功能和更好的性能。WebClient
:不推荐使用,特别是在 .NET Core 和 .NET 5+ 中。