HttpWebRequest invalid contentlength

2020-05-03 12:06发布

问题:

I need to get content length in order to tell my app where the buffer ends. The problem is that httpwebresponse.ContentLength returns -1 even though Content-Length header is presented in response.

Then I though I'm going to read the actual header to find out the length. The Content-Length returned by the page I'm testing on is 1646. An HTTP sniffer claims that I received 1900 bytes, so I assume the difference are the header length. Then I copied the whole body from response and pasted it into online strlen site and the body size is actually 1850!!

How is this possible? Why does response return invalid content-length and why does httpwebrequest.ContentLength returns -1? How can I calculate the actual response length before receiving the response itself?

EDIT: This is the code I'm using to get the response:

                  using (System.IO.Stream responseStream = hwresponse.GetResponseStream())
                  {
                      using (MemoryStream memoryStream = new MemoryStream())
                      {
                          int count = 0;
                          do
                          {
                              count = responseStream.Read(buffer, 0, buffer.Length);
                              TCP_R.SendBytes(buffer);

                          } while (count != 0);

                      }
                  }

                  byte[] PACKET_END_IDENTIFIER = { 0x8, 0x01, 0x8, 0x1, 0x8 };
                  TCP_R.SendBytes(PACKET_END_IDENTIFIER);
                  TCP_R.Close();

I have a proxy server application that takes a request, sends it to another application (my client) client executes the request and using TCP_R class returns the result. When server gets response from client, it returns response back to browser.

Each time I do a request, I get all the data + extra garbage, here's an example:

<tag1><tag2><tag3> ag3> 

ag3> is the garbage data, it's like the ending of buffer is cut off and added again. It apprears that the client responds with a valid response, the garbage data is added onDataRecieve event.. any tips? thanks!

回答1:

-1 isn't an invalid value of the ContentLength property. I assume you mean the ContentLength property of the response is -1... asking the request what the length is would be non-sensical. Even so, it's perfectly valid:

The ContentLength property contains the value of the Content-Length header returned with the response. If the Content-Length header is not set in the response, ContentLength is set to the value -1.

If the body length is 1850, that suggests it's using chunked transfer encoding. But that should be transparent to you - just keep reading from the response stream until the end. If you're using .NET 4, it's dead easy - just create a MemoryStream and use Stream.CopyTo to copy the data to that MemoryStream.