2011-04-04 52 views
1

我在我的ASP.Net頁面中使用天氣API。在ASP.Net中的Google Weather API

如果我將語言(hl)添加到查詢中,我將得到此錯誤: 「給定編碼中的字符無效,第1行,第526位」。
它沒有語言的get參數,但我想要本地化輸出。

這裏是我的代碼在第二行錯誤:

XmlDocument doc = new XmlDocument(); 
      doc.Load("http://www.google.com/ig/api?hl=de&weather=" + location); 

這個工程:

XmlDocument doc = new XmlDocument(); 
      doc.Load("http://www.google.com/ig/api?weather=" + location); 

任何想法?

+0

**的谷歌API的天氣是在2012關閉** - > http://stackoverflow.com/questions/12145820/google-weather-api-gone/35943521 – 2016-03-11 15:55:25

回答

3

由於某些原因,Google不是UTF編碼輸出。這裏有一個方法可以讓你來彌補:

WebClient client = new WebClient(); 
string data = client.DownloadString("http://www.google.com/ig/api?hl=de&weather=YourTown"); 

byte[] encoded = Encoding.UTF8.GetBytes(data); 

MemoryStream stream = new MemoryStream(encoded); 

XmlDocument xml = new XmlDocument(); 
xml.Load(stream); 

Console.WriteLine(xml.InnerXml); 
Console.ReadLine(); 
2

你可以把它代替WebClient使用HttpWebRequest像下面這樣做:

HttpWebRequest myRequest; 
HttpWebResponse myResponse= null; 
XmlDocument MyXMLdoc = null; 

myRequest = (HttpWebRequest)WebRequest.Create("http://www.google.com/ig/api" + 
    "?weather=" + string.Format(location)); 
myResponse = (HttpWebResponse)myRequest.GetResponse(); 
MyXMLdoc = new XmlDocument(); 
MyXMLdoc.Load(myResponse.GetResponseStream()); 
相關問題