2017-09-23 81 views
-1

我正在使用谷歌財務轉換爲另一種貨幣。 我正在使用的代碼如下所示,工作正常。但是,今天,我正面臨IndexOutofrange異常,並且在下面搜索到的索引中獲得-1的結果(這意味着我的結果不包含轉換後的值,在記錄日誌後它是100%真實的)C#.net WebRequest谷歌財務

然後我去了到相同的Web請求調用,給它相同的參數,然後檢查來自Web瀏覽器的源代碼,並且我得到了VALUE。

你認爲可能是什麼問題?從Web瀏覽器,我得到整個結果,並從我的應用程序結果是缺少轉換值字段。

private static string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency) 
{ 
    try 
    { 
     //Grab your values and build your Web Request to the API 
     string apiURL = String.Format("https://www.google.com/finance/converter?a={0}&from={1}&to={2}&meta={3}", amount, fromCurrency, toCurrency, Guid.NewGuid().ToString()); 

     //Make your Web Request and grab the results 
     var request = WebRequest.Create(apiURL); 

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

     //Grab your converted value (ie 2.45 USD) 
     String temp = streamReader.ReadToEnd().ToString(); 
     int pFrom = temp.IndexOf("<span class=bld>") + ("<span class=bld>").Length; 
     int pTo = temp.LastIndexOf("</span>"); 

     System.Windows.MessageBox.Show(pFrom.ToString() + " " + pTo.ToString()); 
     String result = temp.Substring(pFrom, pTo - pFrom); 

     // string result = Regex.Matches(streamReader.ReadToEnd(), "<span class=\"?bld\"?>([^<]+)</span>")[0].Groups[1].Value; 

     //Get the Result 
     return result; 
    } 
    catch(Exception ex) 
    { 
     return ""; 
    } 
} 
+0

那麼明顯的第一件事就是將'temp'保存到一個文件中,這樣你就可以看到你正在得到什麼... –

+0

@JonSkeet顯然,我已經這樣做了:D正如我所說即時獲得相同的結果沒有標籤 –

+0

那麼它不是很清楚你是什麼這意味着。如果你這樣說:「當我用瀏覽器獲取它時,我得到這個HTML,當我用'WebRequest'獲取它時,我得到這個HTML」顯示兩者。您查找字符串中不包含的內容的代碼實際上並不重要 - 事實上,您沒有獲得您期望的HTML。 –

回答