1

我想做的是,

我从博客中抓取了以下片段:

string xeString = String.Format("http://www.xe.com/ucc/convert.cgi?Amount=1&From={0}&To={1}", srcCurrency, dstCurrency);
System.Net.WebRequest wreq = System.Net.WebRequest.Create(new Uri(xeString));
System.Net.WebResponse wresp = wreq.GetResponse();
Stream respstr = wresp.GetResponseStream();
int read = respstr.Read(buf, 0, BUFFER_SIZE);
result = Encoding.ASCII.GetString(buf, 0, read);

现在,这将返回类似XE.com: USD to EUR rate: 1.00 USD = 0.716372 EUR

问题是:

  1. 我不知道变量是buf什么BUFFER_SIZE
  2. 如何获得准确的结果,例如5 AZN以美元发送并获得结果(双倍)?http://www.xe.com/ucc/convert/?Amount=5&From=AZN&To=USD
4

2 回答 2

1
  1. http://msdn.microsoft.com/fr-fr/library/system.io.stream.read.aspx

    buf 是一个 byte[] 数组,一旦方法返回,它就会包含您刚刚读取的数据。BUFFER_SIZE 是您要读取的数据的大小。如果要读取单个字节,BUFFER_SIZE=1。如果你想读取一千字节的数据,BUFFER_SIZE=1024 等。注意,如果你要求一个太大的缓冲区(例如,当数据为 1KB 时要求 1MB),这并不重要。它将读取一个 KB,然后返回。

  2. 您的最终字符串应该如下所示,除非 XE.com 决定更改它:

    XE.com:美元兑欧元汇率:1.00 美元 = 0.716372 欧元

    您可以使用 String 方法去除不需要的东西:整个第一部分

    (XE.com: USD to EUR rate:)

    只需使用您的数据构建一个字符串即可轻松删除:

    (string header = "XE.com: {0} to {1} rate:", currency1, currency2)

    ,然后调用String.Replace(header, '')。从那里,您可以调用String.Split('='),在 '=' 符号处拆分,然后从拆分的字符串中删除货币部分(再次,String.Replace()),最后调用Double.TryParse()

注意:codesparkle 的方法更简单,因为您基本上跳过了第 1 步。但是 XE.com 没有提供 API:您不能保证返回的字符串是有效的,或者将来某天不会改变。

好的,这里有一些代码:

private double GetConvertedCurrencyValue(string inputCurrency, string outputCurrency, double value) 
{
    string request = String.Format(http://www.xe.com/ucc/convert.cgi?Amount={0}&From={1}&To={2}", value, inputCurrency, outputCurrency);

    System.Net.WebClient wc = new System.Net.WebClient();
    string apiResponse = wc.DownloadString(request);    // This is a blocking operation.
    wc.Dispose();

    /* Formatting */
    // Typical response: "XE.com: curr1 to curr2 rate: x curr1 = y curr2"
    // The first part, up until "x curr1" is basically a constant
    string header = String.Format("XE.com: {0} to {2} rate:" inputCurrency, outputCurrency);

    // Removing the header
    // The response now looks like this: x curr1 = y curr2
    apiResponse = apiResponse.Replace(header, "");

    // Let's split the response at '=', to retrieve the right part
    string outValue = apiResponse.Split('=')[1];

    // Getting rid of the 'curr2' part
    outValue = outValue.Replace(outputCurrency, "");

    return Double.Parse(outValue, System.Globalization.CultureInfo.InvariantCulture);
}
于 2012-07-08T17:11:54.570 回答
-2

删除了旧代码。这是迄今为止最准确的一个 EDIT2:

string[] words = result.Split(' ');
Double newresult;

foreach(string i in words)
{
    if(Double.TryParse(i) == true)
    {
        if(!Double.Parse(i).equals(inputValue))
        {
            newresult = Double.Parse(i);
            break;
        }
    }
}

这应该几乎尝试将每个单词解析为双精度并忽略等于输入值的双精度(需要转换的数字)。这仍然不是 100% 准确,就好像他们将其他单独的数字添加到它采用该值的字符串中一样。

于 2012-07-08T17:13:02.357 回答