创建TcpClient的使用HTTP请求

创建TcpClient的使用HTTP请求

本文介绍了创建TcpClient的使用HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个空的asp.net web应用程序在那里我有一个简单的aspx页面:

I have created an empty asp.net web application where I have a simple aspx page:

protected void Page_Load(object sender, EventArgs e)
{
    Response.Write("Hello world");
}

当我转到的http://本地主机:2006 /1.aspx 我看到一个页面,上面写着Hello World的。

when i goto http://localhost:2006/1.aspx I see a page that says "Hello world".

确定这样C#的,如果我做的:

WebClient webClient = new WebClient() { Proxy = null };
var response2 = webClient.DownloadString("http://localhost:2006/1.aspx");



然后响应2 ==世界,你好

then response2 == "Hello world"

我试图实现与TCP连接同样的事情,出于某种原因,它确实不工作:

byte[] buf = new byte[1024];
string header = "GET http://localhost:2006/1.aspx HTTP/1.1\r\n" +
                "Host: localhost:2006\r\n" +
                "Connection: keep-alive\r\n" +
                "User-Agent: Mozilla/5.0\r\n" +
                "\r\n";

var client = new TcpClient("localhost", 2006);

// send request
client.Client.Send(System.Text.Encoding.ASCII.GetBytes(header));

// get response
var i = client.Client.Receive(buf);
var response1 = System.Text.Encoding.UTF8.GetString(buf, 0, i);

下面response1!=你好尔德。的(注意我用的!=意不等于)

here response1 != "Hello Wold". (note I use != meaning NOT equal)

在这个例子中,我得到一个错误的请求错误。

In this example I get a bad request error.

我想用学习之用TCP连接。我不明白为什么第二个例子是行不通的。我的第一反应是可能的标题是不正确的所以我所做的是我为了看标题我的浏览器CHROM推出送Wireshark的。 //本地主机:2006 / 1.aspx 是:

I want to use a tcp connection for learning purposes. I dont understand why the second example does not work. My first reaction was maybe the headers are incorrect so what I did is I launched wireshark in order to see the headers send by my chrom browser. In fact the actual request sent by my browser when I goto http://localhost:2006/1.aspx is:

GET http://localhost:2006/1.aspx HTTP/1.1
Host: localhost:2006
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8

我一直在使用这一请求也试过,当我这样做我也得到一个错误的请求的响应!为什么呢?

在换句话说,我已经取代

In other words I have replaced

string header = "GET http://localhost:2006/1.aspx HTTP/1.1\r\n" +
                "Host: localhost:2006\r\n" +
                "Connection: keep-alive\r\n" +
                "User-Agent: Mozilla/5.0\r\n" +
                "\r\n";

有关

string header = "GET http://localhost:2006/1.aspx HTTP/1.1\r\n" +
        "Host: localhost:2006\r\n" +
        "Connection: keep-alive\r\n" +
        "Cache-Control: max-age=0\r\n" +
        "Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\n" +
        "User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36\r\n" +
        "Accept-Encoding: gzip,deflate,sdch\r\n" +
        "Accept-Language: en-US,en;q=0.8" +
        "\r\n\r\n";

和它仍然无法正常工作。

and it still does not work.

推荐答案

下面是我的版本。正常工作

Here is my version. Works fine

    private static async Task<string> HttpRequestAsync()
    {
        string result = string.Empty;

        using (var tcp = new TcpClient("www.bing.com", 80))
        using (var stream = tcp.GetStream())
        {
            tcp.SendTimeout = 500;
            tcp.ReceiveTimeout = 1000;
            // Send request headers
            var builder = new StringBuilder();
            builder.AppendLine("GET /?scope=images&nr=1 HTTP/1.1");
            builder.AppendLine("Host: www.bing.com");
            //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);

            // Send payload data if you are POST request
            //await stream.WriteAsync(data, 0, data.Length);

            // receive data
            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());
                    }
                }
                else
                {
                    result = Encoding.UTF8.GetString(data, index, data.Length - index);
                    //result = Encoding.GetEncoding("gbk").GetString(data, index, data.Length - index);
                }
            }

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

    private static int BinaryMatch(byte[] input, byte[] pattern)
    {
        int sLen = input.Length - pattern.Length + 1;
        for (int i = 0; i < sLen; ++i)
        {
            bool match = true;
            for (int j = 0; j < pattern.Length; ++j)
            {
                if (input[i + j] != pattern[j])
                {
                    match = false;
                    break;
                }
            }
            if (match)
            {
                return i;
            }
        }
        return -1;
    }

这篇关于创建TcpClient的使用HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 17:48