c#web请求html响应显示不好

时间:2018-03-31 20:17:34

标签: c# html browser tcp webrequest

我正在尝试使用tcp和http请求检索网站,我添加了一个文本框和一个Go按钮,我在文本框中键入地址,然后按下按钮进入网站。它运行良好,除了它没有显示我完整的页面,例如当我尝试访问www.google.com时,它不会显示谷歌徽标,它也不断给我关于js文件的警告。 这是我的代码的主要部分,非常感谢任何帮助。

private async void button1_ClickAsync(object sender, EventArgs e)
        {
            string result = string.Empty;

            using (var tcp = new TcpClient(textBox1.Text, 80))
            using (var stream = tcp.GetStream())
            {
                tcp.SendTimeout = 500;
                tcp.ReceiveTimeout = 1000;
                var builder = new StringBuilder();
                builder.AppendLine("GET /?scope=images&nr=1 HTTP/1.1");
                builder.AppendLine("Host: " + textBox1.Text);
                //builder.AppendLine("Content-Length: " + data.Length);   // only for POST request
                builder.AppendLine("Connection: close");
                builder.AppendLine();
                var header = Encoding.ASCII.GetBytes(builder.ToString());
                await stream.WriteAsync(header, 0, header.Length);


                //await stream.WriteAsync(data, 0, data.Length);


                using (var memory = new MemoryStream())
                {
                    await stream.CopyToAsync(memory);
                    memory.Position = 0;
                    var data = memory.ToArray();

                    var index = BinaryMatch(data, Encoding.ASCII.GetBytes("\r\n\r\n")) + 4;
                    var headers = Encoding.ASCII.GetString(data, 0, index);
                    memory.Position = index;

                    if (headers.IndexOf("Content-Encoding: gzip") > 0)
                    {
                        using (GZipStream decompressionStream = new GZipStream(memory, CompressionMode.Decompress))
                        using (var decompressedMemory = new MemoryStream())
                        {
                            decompressionStream.CopyTo(decompressedMemory);
                            decompressedMemory.Position = 0;
                            result = Encoding.UTF8.GetString(decompressedMemory.ToArray());
                            webBrowser2.DocumentText = result;
                        }
                    }
                    else
                    {
                        result = Encoding.UTF8.GetString(data, index, data.Length - index);
                        webBrowser2.DocumentText = result;
                        //result = Encoding.GetEncoding("gbk").GetString(data, index, data.Length - index);
                    }
                }

                //Debug.WriteLine(result);
                //return result;
            }
            }

0 个答案:

没有答案