6

I'm just getting started messing around with the SO API. I haven't worked with JSON before, and I am getting a strange result from a basic call (No API Key).

WebClient stackClient = new WebClient();
string result = stackClient.DownloadString(@"http://api.stackoverflow.com/0.8/stats");

The result is:

‹í½I–%&/mÊ{JõJ×àt¡€$Ø@ìÁˆÍæ’ìiG#)«*ÊeVe]f@Ìí¼÷Þ{ï½÷Þ{ï½÷º;N'÷ßÿ?\fdlöÎJÚÉž!€ªÈ?~|?"~ñoœ¤éGM›µEÓÓæ£Gé÷ðQšþbùA߶U›•¿ÿ/ZçÔ¢Z¢É§Ÿ~ºs0ê´X/³es•×ùŒšìîܸ{¯ÛDÄîýýƒûûÝÓj±È—-Zì=ع·ói¯—˪͇vwwöº_O²Ù…|ÿpÿþnþº‘î÷öïïݻᄉ£ûýWyýû/ŠåºÍ©ÙÎøÁ×H±›ìŽ?õî{@¼ž²Uñû_ꌾ³T¦oܧíŒ>²¯ÐWu~Y˜ïvÇ;ãݽ{ûãûŸ>8øÈ4ú%ò ÿøþoœü’äÿNïþìÚ

I'm not sure what sort of formatting I'm missing, but this looks like I'm missing something obvious, it just isn't obvious to me.

Any thoughts?

Edited to add a bit of code to decompress the API data:

WebClient stackClient = new WebClient();
byte[] compressedData = stackClient.DownloadData(@"http://api.stackoverflow.com/0.8/stats");
int messageLength = BitConverter.ToInt32(compressedData, 0);

        using (MemoryStream ms = new MemoryStream(compressedData,0,compressedData.Length))
        {
            byte[] decompressedData = new byte[messageLength];
            using (GZipStream gZip = new GZipStream(ms, CompressionMode.Decompress))
            {
                gZip.Read(decompressedData, 0, decompressedData.Length);
            }

            string result = Encoding.UTF8.GetString(decompressedData);
        }

2 Answers 2

7

You are getting the GZipped stream of the response content. Use DownloadData instead of DownloadString and uncompress the stream before passing it to the JSON deserializer (or whatever you plan to use).

Alternatively, you can use the StackOverflow.Net library.

1
  • Thanks, you're a scholar and a gentlemen...StackOverflow.Net looks really nice.
    – denny
    May 23, 2010 at 15:51
4

All responses from the API are compressed. You can specify the compression scheme (gzip or deflate) in the Accept-Encoding header. If you don't specify, one will be chosen for you.

We used to throw up an error when a non-compressed request was received, but a frustrating number of proxies don't pass Accept-Encoding through properly; so instead we silently patch up omissions now.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .