SslStream解密的问题?

时间:2013-07-27 05:44:44

标签: c# .net tcp tcpclient sslstream

我正在使用TcpClient和SslStream向服务器发送https请求,它通常可以工作,我能够看到以明文形式返回的标题,但页面内容是乱码。我不确定我做错了什么。

以下是代码段:

using (var client = new TcpClient("host", 443))
        {
            using (var sslStream = new SslStream(client.GetStream(), true, null, null, EncryptionPolicy.AllowNoEncryption))
            {
                sslStream.AuthenticateAsClient("host", null, SslProtocols.Tls, false);

                using (var writer = new StreamWriter(sslStream))
                using (var reader = new StreamReader(sslStream))
                {
                    writer.AutoFlush = true;
                    writer.WriteLine("GET / HTTP/1.1");
                    writer.WriteLine("Host: host:443");
                    writer.WriteLine("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; rv:22.0) Gecko/20100101 Firefox/22.0");
                    writer.WriteLine("Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
                    writer.WriteLine("Accept-Language: en-US,en;q=0.5");
                    writer.WriteLine("Accept-Encoding: gzip, deflate");
                    writer.WriteLine("Referer: host");
                    writer.WriteLine("Connection: close");
                    writer.WriteLine();
                    writer.WriteLine();


                    Console.WriteLine(reader.ReadToEnd());
                }
            }
        }

写入控制台的示例结果:

HTTP/1.1 200 OK
Server: Apache/2.2.15 (Red Hat) Phusion_Passenger/3.0.17
X-Powered-By: Phusion Passenger (mod_rails/mod_rack) 3.0.17
ETag: "d313c66ae97b1bf4fa81ce11830a40d2"
Content-Language: en
X-Runtime: 3095
Cache-Control: private
Status: 200
Content-Encoding: gzip
P3P: CP="NON DSP CURa ADMa DEVa TAIa PSAa PSDa IVAa IVDa CONa TELa OUR DELa SAMa OTRa IND PHY ONL UNI PUR FIN COM NAV INT CNT STA PRE LOC"
Content-Length: 43543
Content-Type: text/html; charset=utf-8
Date: Sat, 27 Jul 2013 05:41:13 GMT
Connection: close
Vary: Accept-Encoding

?      ???v?H?(
?n?u???S??.J???????U?ZR??o-?$?Q6 Jf????~?p_?F$  ?!?"??Z?Df?SF???????/??B?????N?
;????????????n?NiO???s?????a??$??????0???????H??????;??w?t???????_????0

1 个答案:

答案 0 :(得分:0)

我是个白痴:)反应是gzipped。

添加以下内容可解决问题:

...
using (Stream gzSr = new GZipStream(sslStream, CompressionMode.Decompress)) {
...
}
...