I have a Proxy which handles HTTP Requests.
Now when I get a GZipped HTTP Response, I'm decompressing it like :
MemoryStream ms = new MemoryStream();
if (response.ContentLength > 0)
buffer = new Byte[response.ContentLength];
else
buffer = new Byte[BUFFER_SIZE];
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
string resp = "";
if (response.ContentEncoding == "gzip")
resp = Utilities.GZip.Unzip(ms.ToArray());
else
resp = Encoding.UTF8.GetString(ms.ToArray());
Where Utilities.GZip.Unzip does:
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
CopyTo(gs, mso);
}
return Encoding.UTF8.GetString(mso.ToArray());
}
So far everything's fine, I can read the HTML.
Now I have to Write the Response back to the Client who requested it.
Like this:
byte[] outByte;
if (response.ContentEncoding == "gzip")
outByte = Utilities.GZip.Zip(resp);
else
outByte = Encoding.UTF8.GetBytes(resp);
outStream.Write(outByte, 0, outByte.Length);
Where Utilities.GZip.Zip does:
var bytes = Encoding.UTF8.GetBytes(str);
using (var msi = new MemoryStream(bytes))
using (var mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
{
CopyTo(msi, gs);
}
return mso.ToArray();
}
Now it's a really strange behaviour, the response byte-Array has a Length of 16990 (zipped), but my own zipped byte-Array has a Length of 19379.
The client get's a response, but it's cutted off.
Any suggestions?
EDIT:
For your information, as I send the original MemoryStream unchanged to the Client everythings fine!