HTTP 错误 400。使用 TcpClient 的请求动词无效

HTTP Error 400. The request verb is invalid using TcpClient

我正在使用 Visual Studio 2017 和 VC# 并尝试连接到服务器计算机

如果我使用网络浏览器与此 url:

http://win8pc:6062/lookup/1

我收到这样的回复:

<Response>
     <Error>Transaction 1 is found.</Error>
</Response>

服务器运行正常。

但是当我尝试从 windows.forms 应用连接时,这样做:

string server = "win8pc";
int iport = 6062;
try
{
    TcpClient client = new TcpClient(server, iport);

    // Translate the passed message into ASCII and store it as a Byte array.
    string message = "http://win8pc:6062/lookup/1";
    Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);

    // Get a client stream for reading and writing.
    NetworkStream stream = client.GetStream();

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length);

    // Receive the TcpServer.response.
    // Buffer to store the response bytes.
    data = new Byte[1024];

    // String to store the response ASCII representation.
    String responseData = String.Empty;

    // variable to store bytes received.
    Int32 bytes = 0;

    // Read the first batch of the TcpServer response bytes.
    do
    {
        bytes = stream.Read(data, 0, data.Length);
        if (bytes > 0)
            responseData += System.Text.Encoding.ASCII.GetString(data, 0, bytes);
    } while (bytes > 0);

    // Close everything.
    stream.Close();
    client.Close();
}
catch (ArgumentNullException e)
{
    Console.WriteLine("ArgumentNullException: {0}", e);
}
catch (SocketException e)
{
    Console.WriteLine("SocketException: {0}", e);
}

我在 responseData 中得到的响应是:

HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Server: Microsoft-HTTPAPI/2.0
Date: Thu, 26 Apr 2018 23:02:25 GMT
Connection: close
Content-Length: 326

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<HTML><HEAD><TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii"></HEAD>
<BODY><h2>Bad Request - Invalid Verb</h2>
<hr><p>HTTP Error 400. The request verb is invalid.</p>
</BODY></HTML>

我错过了什么?

问候 鲁本茨

由于服务器用其 "Bad Request" 响应代码告诉您,您没有发送 proper HTTP request。典型的 HTTP GET 请求如下所示:

GET /url HTTP/1.1
Host: www.servername.com
Accept: image/gif, image/jpeg, */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)

以上每一行应以回车符 return 和换行符对 (\r\n) 结尾,整个请求应以空行 (\r\n) 结尾。

也就是说,你几乎肯定不应该自己编写代码,除非它纯粹是一种学习练习。相反,利用内置的 WebRequest API 或类似的东西。在当今时代,HTTP 可以说是 "first-class citizen" 在包括 C#/.NET 在内的许多编程环境中。