开发者

Weird tcpclient https post response

I have a weird problem trying to get full response from a web page using TcpClient which I send a POST to. Here the code:

byte[] RecvBufferxxxx = new byte[4096];

var returnData = "";
var uri = new Uri(string.Format(core.serverAuth, "app_data"));
var head = new WebHeaderCollection();
head[HttpRequestHeader.Host] = uri.Host;
head[HttpRequestHeader.Connection] = "keep-alive";
head[HttpRequestHeader.AcceptEncoding] = "deflate";

using (var client = new TcpClient(uri.Host, 443))
{
    client.SendTimeout = 10000;
    client.ReceiveTimeout = 10000;
    using (SslStream s = new SslStream(client.GetStream(), false, 
        IgnoreCertificateErrorHandler, null))
    {
        s.AuthenticateAsClient(uri.Host, null, SslProtocols.Tls, false);

        var hhd = "POST " + uri.PathAndQuery + " HTTP/1.0\r\n" + head;

        var bts = Encoding.ASCII.GetBytes(hhd);
        s.Write(bts, 0, bts.Length);
        s.Flush();
        s.ReadByte();

        var n = s.Read(RecvBufferxxxx, 0, RecvBufferxxxx.Length);
        // var tmp = Encoding.ASCII.GetString(RecvBufferxxxx, 0, n);
        // ANOTHER CALL SAMPLE   
        // n = s.Read(RecvBufferxxxx, 0, RecvBufferxxxx.Length);

        using (MemoryStream ms = new MemoryStream(RecvBufferxxxx, 0, n))
        {
            ms.ReadByte();
            ms.ReadByte();
            using (DeflateStream df = new DeflateStream(ms, 
                CompressionMode.Decompress))
            {
                using (StreamReader rd = new StreamReader(df))
                {
                    returnData = rd.ReadToEnd();
                }
            }
        }
    }
}

This code works, but it gets only the response headers, I need to make another call to get the response body and i don't know why.

The response is from my server and is very short.

Before I was using only Socket and it was getting all in one call, but now i have rewritten it as in code adding SSL and deflate.

I have check the same link in firefox with firebug and there is only one get and full response.

I have double check it with wireshark and firebug, using firebug and this code wireshark listing looks quite the same.

I can make the second read with this code and then i get the response body, but then i see in wireshark that there was another ssl connection made and i don't want this, i want just as firefox does this.

Another reason is i just want to开发者_运维百科 know why this is happing an dhow to fix these, can someone help me ?


Stream.Read() may not give you the whole buffer, it is allowed to return less. If you want to read the whole stream, you have to call it in a loop until it returns 0.


Ok, found the solution, but not the problem origin, just use ReadByte in loop, don't know why Read has problems, using reflector i was able to find that it could be a problem with SslStream internal buffering, but who knows.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜