首页 快递查询 快递查询示例代码 快递查询[C#]

快递查询示例代码C#

作者: 阅读数:1149 上传时间:2025-04-01

快递查询

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;

//await Express.QueryAsync("sto", "772039437918854");
class Express
{
    // 替换成你的AppKey
    private const string AppKey = "YOUR_APPKEY_HERE";

    public static async Task QueryAsync(string type, string number)
    {
        try
        {
            using (HttpClient client = new HttpClient())
            {
                // 构造请求URL
                string url = $"https://api.jisuapi.com/express/query?" +
                            $"appkey={AppKey}&" +
                            $"type={Uri.EscapeDataString(type)}&" +
                            $"number={Uri.EscapeDataString(number)}";

                // 发送GET请求
                HttpResponseMessage response = await client.GetAsync(url);
                
                // 确保成功响应
                response.EnsureSuccessStatusCode();

                // 读取响应内容
                string responseBody = await response.Content.ReadAsStringAsync();
                JObject result = JObject.Parse(responseBody);

                // 处理API返回状态
                if ((int)result["status"] == 0)
                {
                    // 解析快递信息
                    JToken data = result["result"];
                    Console.WriteLine($"快递公司:{data["type"]}");
                    Console.WriteLine($"运单号:{data["number"]}");
                    Console.WriteLine("物流轨迹:");
                    foreach (var item in data["list"])
                    {
                        Console.WriteLine($"{item["time"]} - {item["status"]}");
                    }
                }
                else
                {
                    Console.WriteLine($"查询失败:{result["status"]} {result["msg"]}");
                }
            }
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求异常:{ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误:{ex.Message}");
        }
    }
	
	static async Task Main(string[] args)
    {
        //await QueryAsync("sf", "123456789");
    }
}