【发布时间】: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 值具有转换后的值。
【问题讨论】:
-
请阅读stackoverflow.com/help/how-to-ask和stackoverflow.com/help/mcve,因为stackoverflow不是代码编写服务。
-
欢迎来到 SO 请阅读How to ask?
-
你的问题是什么?
-
正则表达式 regex = new Regex("rhs: \\\"(\\d*.\\d*)"); var val = regex.Match(response).Groups[1]。值;var val 包含空值
-
"google.com/finance 改为finance.google.com/finance/… 实现这个,一定能解决你的问题
标签: c# asp.net asp.net-mvc api currency