使用Tcp获取http chunked响应

时间:2013-02-26 23:43:43

标签: c# http stream tcpclient networkstream

我想知道怎样才能读取带有Transfer-Encoding块的http响应 我写了一个我正在做的事情的例子。我遇到的一个问题是clientStream.DataAvailable会返回false,即使有更多内容需要阅读但仍未在流中提供。
关于我接近这个方式的其他建议值得欢迎:

StringBuilder response = new StringBuilder();

TcpClient tcpClient = new TcpClient("www.google.com", 80);

string request = "GET http://www.google.com/ HTTP/1.1\r\n";
request += "Host: www.google.com\r\n";
request += "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:19.0) Gecko/20100101 Firefox/19.0\r\n";
request += "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8\r\n";
request += "Accept-Language: en-US,en;q=0.5\r\n";
request += "Accept-Encoding: gzip, deflate\r\n";
request += "Connection: keep-alive\r\n\r\n";

byte[] requestBuffer = Encoding.ASCII.GetBytes(request);
NetworkStream clientStream = tcpClient.GetStream();
clientStream.Write(requestBuffer, 0, requestBuffer.Length);

// Check to see if this NetworkStream is readable.
if (clientStream.CanRead)
{
    byte[] readBuffer = new byte[4096];
    int numberOfBytesRead = 0;

    // Incoming message may be larger than the buffer size.
    do
    {
        numberOfBytesRead = clientStream.Read(readBuffer, 0, readBuffer.Length);

        response.Append(Encoding.ASCII.GetString(readBuffer, 0, numberOfBytesRead));
    }
    while (clientStream.DataAvailable);
}

clientStream.Close();
tcpClient.Close();

Console.Write(response.ToString());

提前谢谢。

0 个答案:

没有答案