首页 > 解决方案 > 使用 WebClient 下载 JSON 会导致奇怪的类似 unicode 的字符?

问题描述

所以我可以在浏览器中向 https://search.snapchat.com/lookupStory?id=itsmaxwyatt发出请求

它会给我返回 JSON,但是如果我通过 Web 客户端执行此操作,它似乎会返回一个非常模糊的字符串?我可以提供这一切,但现在已经截断:

�x��ƽ����������o�Cj�_�����˗��89:�/�[��/�h��#l���ٗC��U。 �gH�,����qOv�_� �_����σҭ

所以,这里是 Csharp 代码:

using var webClient = new WebClient();
webClient.Headers.Add ("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:89.0) Gecko/20100101 Firefox/89.0");
webClient.Headers.Add("Host", "search.snapchat.com");
webClient.DownloadString("https://search.snapchat.com/lookupStory?id=itsmaxwyatt")

我也尝试过没有任何标头的 http rest 客户端,它仍然返回 JSON。

尝试使用编码:

using var webClient = new WebClient();
webClient.Headers[HttpRequestHeader.AcceptEncoding] = "gzip";
webClient.Encoding = Encoding.UTF8;
webClient.Headers.Add ("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:89.0) Gecko/20100101 Firefox/89.0");
webClient.Headers.Add("Host", "search.snapchat.com");
Console.WriteLine(Encoding.UTF8.GetString(webClient.DownloadData("https://search.snapchat.com/lookupStory?id=itsmaxwyatt")));
                

标签: c#

解决方案


在@Progman 评论之后,您只需执行以下操作:

// You can define other methods, fields, classes and namespaces here
class MyWebClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest;
        request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
        return request;
    }
}
void Main()
{
    using var webClient = new MyWebClient();
    webClient.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:89.0) Gecko/20100101 Firefox/89.0");
    webClient.Headers.Add("Host", "search.snapchat.com");
    var str = webClient.DownloadString("https://search.snapchat.com/lookupStory?id=itsmaxwyatt");
    Debug.WriteLine(str);
}

推荐阅读