在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
头检查是否已压缩。如果响应已压缩,我们使用GZipStream
或DeflateStream
解压缩数据,然后使用StreamReader
读取解压缩后的内容。如果响应未压缩,我们直接使用StreamReader
读取内容。