【问题标题】:How to implement currency conversion如何实现货币换算
【发布时间】:2018-06-26 06:34:57
【问题描述】:

我试图实现下面的代码,但它返回一个空值。

[WebMethod]
public decimal ConvertGOOG(decimal amount, string fromCurrency, string toCurrency)
{
    WebClient web = new WebClient();
    string url = string.Format("http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
    string response = web.DownloadString(url);
    Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)");
    var val = regex.Match(response).Groups[1].Value;
    decimal rate = System.Convert.ToDecimal(regex.Match(response).Groups[1].Value);
    return rate;
}

从下面的代码中,我将 val 值设为 null。在这里,我正在尝试将 1 美元转换为 INR。

我也试过这个代码,但得到 403 禁止错误。

var request = WebRequest.Create(apiURL);

//Get the Response
var streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);

//Grab your converted value (ie 2.45 USD)
var result = Regex.Matches(streamReader.ReadToEnd(), "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value;

我曾尝试使用 Google API 进行代码转换,但它仍然返回 null 值。

如何将 1 美元兑换成印度卢比?

[WebMethod]
        public decimal ConvertGOOG(decimal amount, string fromCurrency, string toCurrency)
        {
            WebClient web = new WebClient();
            string apiURL = String.Format("http://finance.google.com/finance/converter?a={0}&from={1}&to={2}", amount, fromCurrency.ToUpper(), toCurrency.ToUpper());
            string response = web.DownloadString(apiURL);
            var split = response.Split((new string[] { "<span class=bld>" }), StringSplitOptions.None);
            var value = split[1].Split(' ')[0];
            decimal rate = decimal.Parse(value, CultureInfo.InvariantCulture);
            return rate;
        }

这是货币转换的最终方法。 var 值具有转换后的值。

【问题讨论】:

标签: c# asp.net asp.net-mvc api currency


【解决方案1】:

请用以下代码更改您的代码

    [WebMethod]
    public decimal ConvertGOOG(decimal amount, string fromCurrency, string toCurrency)
    {
        WebClient web = new WebClient();
        string apiURL = String.Format("http://finance.google.com/finance/converter?a={0}&from={1}&to={2}", amount, fromCurrency.ToUpper(), toCurrency.ToUpper());
        string response = web.DownloadString(apiURL);
        var split = response.Split((new string[] { "<span class=bld>" }), StringSplitOptions.None);
        var value = split[1].Split(' ')[0];
        decimal rate = decimal.Parse(value, CultureInfo.InvariantCulture);
        return rate;
    }

这将返回转换货币

Google 已停止使用 http://www.google.com/ig/calculator?hl=en&q={2}{0}%3D%3F{1}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-08
    • 2012-03-15
    • 1970-01-01
    • 2022-03-13
    • 1970-01-01
    • 1970-01-01
    • 2020-08-29
    • 1970-01-01
    相关资源
    最近更新 更多