首页 汇率查询 汇率查询示例代码 汇率转换[C#]

汇率转换示例代码C#

作者: 阅读数:1125 上传时间:2025-04-23

汇率转换

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

class Exchange
{
    private const string AppKey = "YOUR_APPKEY_HERE"; // 替换为你的真实 appkey

    // 货币转换
    public static async Task ConvertAsync(string from, string to, decimal amount)
    {
        try
        {
			using var client = new HttpClient();
            string url = $"https://api.jisuapi.com/exchange/convert?appkey={AppKey}&from={from}&to={to}&amount={amount}";
            HttpResponseMessage response = await client.GetAsync(url);
            response.EnsureSuccessStatusCode();

            string result = await response.Content.ReadAsStringAsync();
            JObject jsonarr = JObject.Parse(result);

            if ((int)jsonarr["status"] != 0)
            {
                Console.WriteLine(jsonarr["msg"]);
                return;
            }

            JObject resultObj = (JObject)jsonarr["result"];
            Console.WriteLine($"{resultObj["from"]} {resultObj["to"]} {resultObj["fromname"]} {resultObj["toname"]} {resultObj["updatetime"]} {resultObj["rate"]} {resultObj["camount"]}");
        }
        catch (HttpRequestException ex)
        {
            Console.WriteLine($"请求出错: {ex.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"发生错误: {ex.Message}");
        }
    }

    static async Task Main()
    {
        // 调用货币转换方法
        await Exchange.ConvertAsync("CNY", "USD", 10);
        // 调用查询单一货币信息方法
        await Exchange.SingleAsync("CNY");
        // 调用查询所有货币信息方法
        await Exchange.CurrencyAsync();
        // 十大银行外汇牌价
        await Exchange.BankAsync("BOC");
    }
}