温馨提示×

c# httpwebrequest怎样处理压缩

c#
小樊
81
2024-11-16 20:43:53
栏目: 编程语言

在C#中,使用HttpWebRequest处理压缩的响应,你需要检查响应头中的Content-Encoding字段,以确定响应是否已压缩。如果响应已压缩,你需要使用相应的解压缩算法来解压数据。以下是一个示例,展示了如何使用HttpWebRequest获取和解压响应内容:

using System;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Text;

class Program
{
    static void Main()
    {
        string url = "https://example.com/compressed-data";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        request.Method = "GET";
        request.Headers["Accept-Encoding"] = "gzip, deflate"; // 请求压缩响应

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            if (response.Headers["Content-Encoding"] == "gzip")
            {
                using (Stream compressedStream = response.GetResponseStream())
                {
                    using (GZipStream decompressedStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (StreamReader reader = new StreamReader(decompressedStream, Encoding.UTF8))
                        {
                            string content = reader.ReadToEnd();
                            Console.WriteLine("解压缩后的内容: " + content);
                        }
                    }
                }
            }
            else if (response.Headers["Content-Encoding"] == "deflate")
            {
                using (Stream compressedStream = response.GetResponseStream())
                {
                    using (DeflateStream decompressedStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                    {
                        using (StreamReader reader = new StreamReader(decompressedStream, Encoding.UTF8))
                        {
                            string content = reader.ReadToEnd();
                            Console.WriteLine("解压缩后的内容: " + content);
                        }
                    }
                }
            }
            else
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
                {
                    string content = reader.ReadToEnd();
                    Console.WriteLine("未压缩的内容: " + content);
                }
            }
        }
    }
}

在这个示例中,我们首先创建一个HttpWebRequest实例,并设置Accept-Encoding头以请求压缩响应。然后,我们获取响应并使用Content-Encoding头检查是否已压缩。如果响应已压缩,我们使用GZipStreamDeflateStream解压缩数据,然后使用StreamReader读取解压缩后的内容。如果响应未压缩,我们直接使用StreamReader读取内容。

0