惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

I
InfoQ
G
Google Developers Blog
Engineering at Meta
Engineering at Meta
月光博客
月光博客
博客园 - 聂微东
博客园 - Franky
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
有赞技术团队
有赞技术团队
A
About on SuperTechFans
Microsoft Azure Blog
Microsoft Azure Blog
Blog — PlanetScale
Blog — PlanetScale
U
Unit 42
T
Tailwind CSS Blog
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
云风的 BLOG
云风的 BLOG
S
SegmentFault 最新的问题
F
Fortinet All Blogs
H
Help Net Security
J
Java Code Geeks
酷 壳 – CoolShell
酷 壳 – CoolShell
博客园 - 叶小钗
L
LangChain Blog
Martin Fowler
Martin Fowler
N
Netflix TechBlog - Medium

zodream梦想开源/个人编程日记

文件解析笔记-zodream梦想开源/个人编程日记 密码本开发笔记之读写与保存-zodream梦想开源/个人编程日记 SkiaSharp 把 pixel byte[] 转成 SKBitmap-zodream梦想开源/个人编程日记 nas 使用 Docker 安装 gogs-zodream梦想开源/个人编程日记 复制 android 手机中的文件到电脑-zodream梦想开源/个人编程日记 周报:寻找优质的周刊-zodream梦想开源/个人编程日记 开发日志:对Markdown的代码块新增引用来源支持-zodream梦想开源/个人编程日记 周报:怎么写技术类的教程文章-zodream梦想开源/个人编程日记 css display:flex 布局尺寸超出问题-zodream梦想开源/个人编程日记 周报:SEO优化的思考-zodream梦想开源/个人编程日记 Edge 浏览器不适用 Edge Image Viewer 打开图片 -zodream梦想开源/个人编程日记 SEO 学习笔记(一) 内容来源-zodream梦想开源/个人编程日记 PHP 实现双因素身份认证(2FA)-zodream梦想开源/个人编程日记 WPF MVVM 获取List 多选数据-zodream梦想开源/个人编程日记 Burp Suite 抓包-zodream梦想开源/个人编程日记 使用 indexnow 注意事项-zodream梦想开源/个人编程日记 Godot 使用字体图标 例如: Iconfont、FontAwesome-zodream梦想开源/个人编程日记 angular 15 对指定页面进行访问限制-zodream梦想开源/个人编程日记 CSS 使用 column-count 实现瀑布流出现内容分割的解决办法-zodream梦想开源/个人编程日记 input 确认按键事件在手机端不生效-zodream梦想开源/个人编程日记 C# 使用socket 进行通讯-zodream梦想开源/个人编程日记 Maui开发中Windows应用开启管理员权限-zodream梦想开源/个人编程日记 Maui 中自定义控件-zodream梦想开源/个人编程日记 angular 14 使用 ng-template 实现tree 结构显示-zodream梦想开源/个人编程日记 c# 动态安装和卸载dll-zodream梦想开源/个人编程日记 慎用 CompositionTarget.Rendering-zodream梦想开源/个人编程日记 c# 重写 c++ 程序笔记:数据初始化-zodream梦想开源/个人编程日记 源码编译 aseprite-zodream梦想开源/个人编程日记 记录一下字符串分隔split各语言之间的不同-zodream梦想开源/个人编程日记 c# Gzip解码无头内容-zodream梦想开源/个人编程日记
UWP 解压 GZIP-zodream梦想开源/个人编程日记
zodream · 2017-10-28 · via zodream梦想开源/个人编程日记

准备工作:

通过 NUGET 安装 Microsoft.Bcl.Compression ;

使用命名空间

using System.IO.Compression ;

public static async Task Get(string url)
{
    WebRequest request = WebRequest.CreateHttp(new Uri(url)); //创建WebRequest对象              
    request.Method = "GET";    //设置请求方式为GET
    request.Headers[HttpRequestHeader.UserAgent] = "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0";
    request.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate"; //设置接收的编码 可以接受 gzip            
    var response = await request.GetResponseAsync();
    Stream stream = null;
    stream = response.Headers[HttpRequestHeader.ContentEncoding].Equals("gzip",
        StringComparison.CurrentCultureIgnoreCase) ? 
        new GZipStream(response.GetResponseStream(), CompressionMode.Decompress) : response.GetResponseStream();            
    var ms = new MemoryStream();            
    var buffer = new byte[1024];            
    while (true)
    {                
        if (stream == null) continue;                
        var sz = stream.Read(buffer, 0, 1024);                
        if (sz == 0) break;
        ms.Write(buffer, 0, sz);
    }            
    var bytes = ms.ToArray();
    var html = GetEncoding(bytes, response.Headers[HttpRequestHeader.ContentType]).GetString(bytes);            
    await stream.FlushAsync();            
    return html;
}

12345678910111213141516171819202122232425262728

获取编码:

public static Encoding GetEncoding(byte[] bytes, string charSet)
{
    var html = Encoding.UTF8.GetString(bytes);
    var regCharset = new Regex(@"charset\b\s*=\s*""*(?<charset>[^""]*)");
    if (regCharset.IsMatch(html))
    {
        return Encoding.GetEncoding(regCharset.Match(html).Groups["charset"].Value);
    }
    if (string.IsNullOrEmpty(charSet))
    {
        return Encoding.UTF8;
    }
    try
    {
        // 解决 gbk gb2312
        Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
        return Encoding.GetEncoding(charSet);
    }
    catch (Exception)
    {
        return Encoding.UTF8;
    }
}

123456789101112131415161718192021222324

虽然使用 HttpClient 更简单

var http = new HttpClient();
http.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (Windows NT 10.0; WOW64; rv:44.0) Gecko/20100101 Firefox/44.0");
http.DefaultRequestHeaders.Add("accept-encoding", "gzip, deflate");            
var response = await http.GetAsync(new Uri(url));
response.EnsureSuccessStatusCode();//确保请求成功

123456

但是它的响应头并没有 Content-Encoding ,所以无法直接判断需不需要 Gzip 解压。

转载请保留原文链接: https://zodream.cn/blog/id/9.html