Stop webclient from escaping strings

偶尔善良 提交于 2019-12-12 21:08:05

问题


I want to use the Google Maps API to geocode/reverse-geocode coordinates/addresses. To do this, I use an instance of C#'s webclient class.

static string gMapsUrl= "http://maps.googleapis.com/maps/api/geocode/xml?address=  {0}&sensor=false";
public static List<Location> RetrieveCoordinate(string address)
{
    string requestUri = string.Format(gMapsUrl, address);
    string result = string.Empty;

    using (var client = new WebClient())
    {
        client.Encoding = System.Text.Encoding.UTF8;
        result = client.DownloadString(requestUri);
    }
....
}

This usually works, however lets say I want to reverse-geocode the address "Götznerstraße". If I do this manually in a browser, everything works fine, the URL of the request would be

http://maps.googleapis.com/maps/api/geocode/xml?address=götznerstraße&sensor=false

The eventual request from my program however looks like this

GET /maps/api/geocode/xml?address=G%C3%B6tznerstra%C3%9Fe&sensor=false HTTP/1.1 

This leads to Google finding no matches. To me it appears as if the webclient escapes the umlaute somewhere, which prevents me from getting results. Is there a way to stop the webclient from doing this, or make Google unescape the string again?

EDIT: I solved it, after comparing the request from the browser and my program, I realized that my browser was sending some additional headers. The changed implementation looks like this

using (var client = new WebClient())
{
    client.Headers.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
    client.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
    client.Headers.Add("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
    client.Encoding = System.Text.Encoding.UTF8;
    result = client.DownloadString(requestUri);
}

Thanks a lot to everyone that helped!


回答1:


It has to escape the url. However there is nothing stopping you from using HttpUtility.UrlDecode to unescape it. Also have a look here for a more indepth answer.




回答2:


I think the problem is actually just that Google doesn't quite know what to do with götznerstraße.

do you actually mean götzner straße?

Regardless, G%C3%B6tznerstra%C3%9Fe is the correct encoding of "götznerstraße", and the encoding is not causing your issue.



来源:https://stackoverflow.com/questions/21375446/stop-webclient-from-escaping-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!