我试图实现下面的代码,但它返回一个空值。
[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进行代码转换,但仍然返回空值。
如何将1美元转换为INR?
[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值具有转换后的值。
答案 0 :(得分:0)
请使用以下代码更改您的代码
[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;
}
这将返回转换货币