我正在使用Visual Studio 2017和VC#并尝试连接到服务器计算机
如果我使用带有此网址的网络浏览器:
我收到这样的回复:
<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>
我错过了什么?
此致 rubenc
答案 0 :(得分:1)
当服务器告诉您“错误请求”响应代码时,您没有发送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)
上面的每一行都应以回车符和换行符对(\r\n
)结束,整个请求应以空行(\r\n
)结束。
那就是说,你几乎肯定不应该自己编码,除非它纯粹是一个学习练习。相反,利用内置的WebRequest API或类似的东西。在这个时代,HTTP是一流的“公民”,可以说在包括C#/ .NET在内的许多编程环境中。