2011-04-04 54 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()); 
相关问题