开发者

Google Weather Api in ASP.Net

I use the weather API in my ASP.Net page.

If I add the language (hl) to the query, I will get this error: "Invalid character in the given encoding. 开发者_如何学编程Line 1, position 526.".

It works without the get parameter for language, but I want to localize the output.

Here is my code with the error in second line:

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

this works:

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

Any idea?


For some reason, Google isn't UTF encoding the output. Here is a way for you to compensate:

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();


You can do it using HttpWebRequest in place of WebClient as like below:

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());  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜