使用 WebClient 下载 JSON 会导致奇怪的类似 unicode 的字符?

Downloading JSON with WebClient results in weird unicode-like characters?

提问人:async life 提问时间:6/17/2021 最后编辑:async life 更新时间:6/17/2021 访问量:171

问:

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

它会给我一个 JSON,但是如果我通过 Web 客户端执行此操作,它似乎会给我一个非常混淆的字符串?我可以提供所有内容,但现在被截断了:

x ƽ o Cjnjivenko _ ˗ 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#

评论

3赞 Progman 6/17/2021
这回答了你的问题吗?通过 WebClient.DownloadData 自动解压 gzip 响应
0赞 Josh Hallow 6/17/2021
所以我用这种方法的代码示例更新了我的问题,但仍然非常隐晦的响应。

答:

1赞 Leonardo Herrera 6/17/2021 #1

根据@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);
}