【问题标题】:Google Weather Api in ASP.NetASP.Net 中的谷歌天气 API
【发布时间】:2011-07-29 09:53:18
【问题描述】:
我在我的 ASP.Net 页面中使用天气 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 );
有什么想法吗?
【问题讨论】:
标签:
asp.net
api
weather
google-weather-api
【解决方案1】:
出于某种原因,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】:
您可以使用HttpWebRequest 代替WebClient 来执行此操作,如下所示:
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());