HTTP错误400.使用TCPCLIENT,请求动词无效



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

如果我使用此URL的Web浏览器:

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);
}

我在响应中得到的响应是:

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>

我缺少什么?

问候rubenc

当服务器告诉您其"不良请求"响应代码时,您没有发送适当的HTTP请求。典型的http获取请求如下:

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)

上面的每条线应以返回和线馈对(rn(结束,并且整个请求应以空白行(rn(结束。

也就是说,您几乎可以肯定不应该自己编码,除非纯粹是一种学习练习。取而代之的是,利用内置的WebRequest API或类似的东西。在这个时代,HTTP是一个"一流的公民",可以在许多编程环境中发言。

最新更新