Eaton
Eaton

Reputation: 1320

Setting HttpWebRequest's AutomaticDecompression causes response ContentLength of -1

Upon setting the HttpWebRequest.AutomaticDecompression to gzip, the response's ContentLength property returns -1. (Before you say it, yes, there IS response content!) This is a big problem because I cannot create my byte array with the amount of bytes I need to read from the response stream.

I analyzed the response in Fiddler and the ContentLength property is correct, .NET doesn't seem to want to use it..

Without the AutomaticDecompression property set, the response ContentLength returns a positive, expected value.

I'd like to take advantage of the built-in decompression. Any ideas why this is happening?

My code:

        var request = (HttpWebRequest)WebRequest.Create(URI);
        request.ReadWriteTimeout = 300000;
        request.Timeout = 300000;
        request.ImpersonationLevel = TokenImpersonationLevel.Anonymous;
        request.Method = RequestMethod;
        if (RequestDetails.GzipCompress) request.Headers.Add("Accept-Encoding", "gzip");
        request.Accept = RequestDetails.Accept;
        request.ContentType = RequestDetails.ContentType;
        request.KeepAlive = RequestDetails.KeepAlive;
        request.ServicePoint.Expect100Continue = false;
        request.UserAgent = "UA";
        request.CookieContainer = null;
        request.Proxy = null;
        request.AutomaticDecompression = DecompressionMethods.GZip;
        if (RequestDetails.CustomHeaders != null) foreach (var pair in RequestDetails.CustomHeaders) request.Headers.Add(pair.Key, pair.Value);
        if (RequestData != null && RequestData.Length > 0)
        {
            request.ContentLength = RequestData.Length;
            using (var ps = request.GetRequestStream())
            {
                ps.Write(RequestData, 0, RequestData.Length);
            }   
        }
        HttpWebResponse response;
        try { response = (HttpWebResponse)request.GetResponse(); }
        catch (WebException ex) { response = (HttpWebResponse)ex.Response; }
        if (!request.HaveResponse || response == null) throw new Exception("No response! The operation may have timed out.");
        byte[] responseData = null;
        if (response.ContentLength > 0) //-1!!!

Upvotes: 1

Views: 3678

Answers (1)

Eaton
Eaton

Reputation: 1320

Fixed. Had to do response.Headers[HttpResponseHeader.ContentLength].

Please note though, this is the size of the COMPRESSED data. Fortunately, in my case, the server I connect to sends back an HTTP header containing the size of the decompressed content length. If yours doesn't, I guess the only way to read all the data is to declare a static large-sized buffer, and read the response stream until it returns 0 bytes read.

Upvotes: 1

Related Questions