Researching the issue led me to the following Stack Overflow articles:
- http://stackoverflow.com/questions/7137165/webclient-downloadstring-results-in-mangled-characters-due-to-encoding-issues-b
- http://stackoverflow.com/questions/4716470/webclient-downloadstring-returns-string-with-peculiar-characters
The accepted answers on both work well, so I've put together a functional example using C# to illustrate the behavior and results.
DownloadString (no encoding specified)
// variables string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU"; // DownloadString (no encoding specified) using (WebClient client = new WebClient()) { Console.WriteLine(client.DownloadString(Url)); } // result [ { "capital": "Hagåtña Dededo" } ]
DownloadString (encoding specified)
// variables string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU"; // DownloadString (encoding specified) using (WebClient client = new WebClient()) { // specify encoding client.Encoding = System.Text.UTF8Encoding.UTF8; // output Console.WriteLine(client.DownloadString(Url)); } // result [ { "capital": "Hagåtña Dededo" } ]
DownloadData (encoding specified)
// variables string Url = "https://mysafeinfo.com/api/data?list=states&format=json&alias=nm=name,ab=code,cp=capital,yr=year&select=capital&ab=GU"; // DownloadData (encoding specified) using (WebClient client = new WebClient()) { Console.WriteLine(System.Text.UTF8Encoding.UTF8.GetString(client.DownloadData(Url))); } // result [ { "capital": "Hagåtña Dededo" } ]
Click here to see a fully functional demo.
Matt Pavey is a Microsoft Certified software developer who specializes in ASP.Net, VB.Net, C#, AJAX, LINQ, XML, XSL, Web Services, SQL, jQuery, and more. Follow on Twitter @matthewpavey
0 comments: