溫馨提示×

c# webclient能進行壓縮傳輸嗎

c#
小樊
81
2024-11-18 22:27:28
欄目: 編程語言

是的,C# WebClient 支持使用 gzip 或 deflate 壓縮傳輸。要實現(xiàn)這一點,您需要在發(fā)送請求時設(shè)置請求頭 “Accept-Encoding” 為 “gzip, deflate”,并在接收響應(yīng)時處理壓縮數(shù)據(jù)。以下是一個簡單的示例:

using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

class Program
{
    static async Task Main(string[] args)
    {
        string url = "https://example.com/some-resource";

        using (HttpClient client = new HttpClient())
        {
            // 設(shè)置請求頭以支持壓縮
            client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("gzip"));
            client.DefaultRequestHeaders.AcceptEncoding.Add(new System.Net.Http.Headers.StringWithQualityHeaderValue("deflate"));

            // 發(fā)送請求并獲取響應(yīng)
            HttpResponseMessage response = await client.GetAsync(url);

            // 檢查響應(yīng)是否為壓縮格式
            if (response.Content.Headers.ContentEncoding.Any(encoding => encoding.Value == "gzip"))
            {
                // 讀取壓縮內(nèi)容并解壓縮
                using (Stream compressedStream = await response.Content.ReadAsStreamAsync())
                using (GZipStream decompressedStream = new GZipStream(compressedStream, CompressionMode.Decompress))
                using (StreamReader reader = new StreamReader(decompressedStream))
                {
                    string content = await reader.ReadToEndAsync();
                    Console.WriteLine("解壓縮后的內(nèi)容: " + content);
                }
            }
            else if (response.Content.Headers.ContentEncoding.Any(encoding => encoding.Value == "deflate"))
            {
                // 讀取壓縮內(nèi)容并解壓縮
                using (Stream compressedStream = await response.Content.ReadAsStreamAsync())
                using (DeflateStream decompressedStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
                using (StreamReader reader = new StreamReader(decompressedStream))
                {
                    string content = await reader.ReadToEndAsync();
                    Console.WriteLine("解壓縮后的內(nèi)容: " + content);
                }
            }
            else
            {
                // 如果沒有壓縮,直接讀取內(nèi)容
                using (StreamReader reader = new StreamReader(response.Content.ReadAsStreamAsync()))
                {
                    string content = await reader.ReadToEndAsync();
                    Console.WriteLine("內(nèi)容: " + content);
                }
            }
        }
    }
}

在這個示例中,我們首先創(chuàng)建了一個 HttpClient 實例,并設(shè)置了請求頭以支持 gzip 和 deflate 壓縮。然后,我們發(fā)送一個 GET 請求并獲取響應(yīng)。接下來,我們檢查響應(yīng)內(nèi)容是否為壓縮格式,并根據(jù)需要解壓縮內(nèi)容。最后,我們輸出解壓縮后的內(nèi)容。

0