无法解析的 StackExchange API 响应

Unparseable StackExchange API response

我已经编写了一个小程序来分析来自 StackExchange API 的个人资料数据,但是 api returns unparse-/unreadable 数据给我。

收到数据:(使用c#自行下载)

\u001f�\b[=13=][=13=][=13=][=13=][=13=]\u0004[=13=]mRMo�0\f�/:�d$�c˱�'�^{/\u0006��\u0018G�>\I��\u0015���\u0004݀�D>�GR�L'���o��\u0004�G���%JP\u001c����-��Em>0���X�bm~�\u0018tk��\u0014�M]r�dLG�v0~Fj=���1\u00031I�>kTRA\"(/+.����;Nl\u0018�?h�\u0014��P藄�X�aL��w���#�3\u0002��+�\u007f���\u0010���\u000f�p�]��v\u007f���\t��ڧ�\nf��״\u0018\u0014eƺ�_��1x#j^-�c� � AX\t���\u001aT��@qj\u001aU7�����\u0014\"\a^\b�#\u001e��QG��%�y�\t�ח������q00K\av\u0011{ظ���\u0005\"\u001d+|\u007f���'�\u0016~��8\u007f�\u0001-h�]O\u007fV�o\u007f\u0001~Y\u0003��\u0002[=13=][=13=]

需要的数据:(从我的浏览器复制粘贴)

{"items":[{"badge_counts",{"bronze":987,"silver":654,"gold":321},"account_id":123456789,"is_employee":false,"last_modified_date":1250612752,"last_access_date":1250540770,"age":0,"reputation_change_year":987,"reputation_change_quarter":654,"reputation_change_month":321,"reputation_change_week":98,"reputation_change_day":76,"reputation":9876,"creation_date":1109670518,"user_type":"registered","user_id":123456789,"accept_rate":0,"location":"Australia","website_url":"http://example.org","link":"http://example.org/username","profile_image":"http://example.org/username/icon.png","display_name":"username"}],"has_more":false,"quota_max":300,"quota_remaining":300}

我写了这个(扩展)方法来从互联网上下载一个字符串:

public static string DownloadString(this string link)
{
    WebClient wc = null;
    string s = null;
    try
    {
        wc = new WebClient();
        wc.Encoding = Encoding.UTF8;
        s = wc.DownloadString(link);
        return s;
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        if (wc != null)
        {
            wc.Dispose();
        }
    }
    return null;
}

然后我在互联网上搜索并找到了一种使用其他策略下载字符串的方法:

public string DownloadString2(string link)
{
    WebClient client = new WebClient();
    client.Encoding = Encoding.UTF8;
    Stream data = client.OpenRead(link);
    StreamReader reader = new StreamReader(data);
    string s = reader.ReadToEnd();
    data.Close();
    reader.Close();
    return s;
}

但是两种方法return相同的(unread-/unparseable)数据。

如何从 API 中获取可读数据?有什么遗漏吗?

在我看来,输出被压缩了。您可以使用 System.IO.Compression 中的 GZipStream 来解压缩字节。

public static string DownloadString(this string link)
{
    WebClient wc = null;
    try
    {
        wc = new WebClient();
        wc.Encoding = Encoding.UTF8;
        byte[] b = wc.DownloadData(link);

        MemoryStream output = new MemoryStream();
        using (GZipStream g = new GZipStream(new MemoryStream(b), CompressionMode.Decompress))
        {
            g.CopyTo(output);
        }

        return Encoding.UTF8.GetString(output.ToArray());
    }
    catch
    {

    }
    finally
    {
        if (wc != null)
        {
            wc.Dispose();
        }
    }
    return null;
}

如您所见 - 您使用的编码错误 -