gpt4 book ai didi

C# Webclient.DownloadData 只返回垃圾

转载 作者:行者123 更新时间:2023-12-04 08:12:03 27 4
gpt4 key购买 nike

我有以下代码,用于下载网络地址的 html 源代码,但是当我运行它时,我只会得到随机字符和很多问号作为输出。
编码:

 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(
delegate
{
return true;
});
using (WebClient webClient = new WebClient())
{
webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
webClient.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webClient.Headers["Accept-Language"] = "en-us,en;q=0.5";
webClient.Headers["Accept-Encoding"] = "gzip,deflate";
webClient.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";

var htmlData = webClient.DownloadData("https://de.WEBSITE.com/EXAMPLE");
var htmlCode = Encoding.UTF8.GetString(htmlData);

Console.WriteLine(htmlCode);
}

最佳答案

这只是因为您正在下载 gzip 压缩的数据。
您应该解压缩数据,然后将其转换为 UTF-8。

webClient.Headers["User-Agent"] = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6 (.NET CLR 3.5.30729)";
webClient.Headers["Accept"] = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
webClient.Headers["Accept-Language"] = "en-us,en;q=0.5";
webClient.Headers["Accept-Encoding"] = "gzip,deflate";
webClient.Headers["Accept-Charset"] = "ISO-8859-1,utf-8;q=0.7,*;q=0.7";

var htmlData = webClient.DownloadData("https://de.WEBSITE.com/EXAMPLE");
using (var msi = new MemoryStream(htmlData))
using (var mso = new MemoryStream()) {
using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
gs.CopyTo(mso);
}

var htmlCode = Encoding.UTF8.GetString(mso.ToArray());
Console.WriteLine(htmlCode);
}

关于C# Webclient.DownloadData 只返回垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65905193/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com