c# - 使用 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")));
解决方案
在@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);
}
推荐阅读
- c - 为什么调用 setjmp() 中的函数会出现分段错误?
- java - 如何在 Google Dataflow 中组合两组不同的标识符?
- spring - 具有多租户的 Spring Data Redis
- java - 二进制 XML 文件第 138 行:膨胀类 android.support.design.widget.NavigationView 时出错
- python - 3D 旋转猴头示例上的坐标
- sql - 将通配符用于连接、MS Access 的参数
- json - 在调用 JQ 时从变量中获取要更新的字段名称(不仅仅是值)
- streaming - Google Speech to Text 的 25 秒延迟
- typescript - 我如何等待一个元素有一些使用量角器的文本?
- javascript - 制作一个 HTML 元素数组