在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
讀取內容。