Google Weather Api in ASP.Net

4.2k Views Asked by At

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?

2

There are 2 best solutions below

0
On BEST ANSWER

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

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