开发手册 欢迎您!
软件开发者资料库

.NET(C#)使用HttpClient请求JSON数据的示例代码

本文主要介绍.NET(C#)中,通过使用HttpClient执行http请求,获取服务器端JSON数据的示例代码。

1、JSON数据格式

JSON(JavaScript对象表示法)是一种轻量级的数据交换格式。这种格式对于人类来说很容易读写,对于机器来说,解析和生成都很容易。它是XML更简单和易读的替代方案。JSON的官方Internet media type是application/json

2、请求JSON数据示例代码

using System;using System.Threading.Tasks;using System.Collections.Generic;using System.Net.Http;using System.Net.Http.Headers;using Newtonsoft.Json;namespace HttpClientJson{    class Contributor    {        public string Login { get; set; }        public short Contributions { get; set; }        public override string ToString()        {            return $"{Login,20}: {Contributions} contributions";        }    }    class Program    {        private static async Task Main()        {            using var client = new HttpClient();            client.BaseAddress = new Uri("https://api.github.com");            client.DefaultRequestHeaders.Add("User-Agent", "CJAVAPY BOT"); //在请求标头中,我们指定User-Agent            client.DefaultRequestHeaders.Accept.Add(                    new MediaTypeWithQualityHeaderValue("application/json"));//设置accept标头,告诉JSON是可接受的响应类型            var url = "repos/symfony/symfony/contributors";            HttpResponseMessage response = await client.GetAsync(url);            response.EnsureSuccessStatusCode();            var resp = await response.Content.ReadAsStringAsync();            List contributors = JsonConvert.DeserializeObject>(resp);            contributors.ForEach(Console.WriteLine);        }    }}

该示例生成对Github的GET请求。它找出了Symfony框架的主要贡献者。它使用Newtonsoft.Json来处理JSON。

相关文档:

.Net(C#) Newtonsoft.Json(Json.NET)Json
.NET(C#) Json.Net(newtonsoft)操作处理(解析)JSON数据(LINQ to JSON)
system.net.http.httpclient
.net(C#)后台发送Get和Post请求的几种方法总结
ASP.net Core 2.1 httpclientFactory使用的3种方法
ASP.net Core 使用httpclient PostAsync POST Json数据
.net Core 使用httpclient通过配置Proxy(代理)执行Get和Post请求数据操作
.net(C#) Fluent HTTP (Flurl Get和Post请求)使用方法及示例代码
.NET(C#) HttpClient单例(Singleton)和每次请求new HttpClient对比
httpclient