HttpWebRequest & Native GZip Compression

前端 未结 6 982
生来不讨喜
生来不讨喜 2020-11-29 21:10

When requesting a page with Gzip compression I am getting a lot of the following errors:

System.IO.InvalidDataException: The CRC in GZip footer does

6条回答
  •  时光取名叫无心
    2020-11-29 21:42

    For .NET Core things are a little more involved. A GZipStream is needed as there isn't a property (as of writing) for AutomaticCompression. See my answer here: https://stackoverflow.com/a/44508724/2421277

    Code from answer:

    var req = WebRequest.CreateHttp(uri);
    
    /*
     * Headers
     */
    req.Headers[HttpRequestHeader.AcceptEncoding] = "gzip, deflate";
    
    /*
     * Execute
     */
    try
    {
        using (var resp = await req.GetResponseAsync())
        {
            using (var str = resp.GetResponseStream())
            using (var gsr = new GZipStream(str, CompressionMode.Decompress))
            using (var sr = new StreamReader(gsr))
    
            {
                string s = await sr.ReadToEndAsync();  
            }
        }
    }
    catch (WebException ex)
    {
        using (HttpWebResponse response = (HttpWebResponse)ex.Response)
        {
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                string respStr = sr.ReadToEnd();
                int statusCode = (int)response.StatusCode;
    
                string errorMsh = $"Request ({url}) failed ({statusCode}) on, with error: {respStr}";
            }
        }
    }
    

提交回复
热议问题