C# 从http接口获取json

在 C# 中,你可以使用多种方法从 HTTP 接口获取 JSON 数据。以下是几种常见的方法,包括使用 HttpClientWebClient。这里我们主要使用 HttpClient,因为它提供了更多的功能和更好的性能。接口请替换使用对应的您需要访问的url。

使用 HttpClient

HttpClient 是 .NET 中用于发送 HTTP 请求和接收 HTTP 响应的推荐类。以下是一个示例,展示如何从指定的 URL 获取 JSON 数据并解析它。

1. 安装必要的 NuGet 包

确保你已经安装了 System.Net.HttpNewtonsoft.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}");
            }
        }
    }
}

详细说明

  1. 创建 HttpClient 实例

    • HttpClient 是一个可重用的对象,建议在整个应用程序生命周期中只创建一次实例。在这里,我们使用 using 语句来确保资源被正确释放。
  2. 发送 GET 请求

    • client.GetAsync(url) 发送一个异步的 GET 请求到指定的 URL,并返回一个 HttpResponseMessage 对象。
  3. 检查响应状态码

    • response.IsSuccessStatusCode 检查响应是否成功(状态码在 200-299 之间)。
  4. 读取响应内容

    • response.Content.ReadAsStringAsync() 读取响应的内容并将其作为字符串返回。
  5. 解析 JSON

    • 使用 Newtonsoft.Json 库中的 JObject.Parse 方法将 JSON 字符串解析为 JObject 对象。
  6. 打印 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+ 中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值