如何使用NetworkStream类发出GET请求?

时间:2015-01-22 21:09:36

标签: c# .net sockets http

我正在尝试使用NetworkStream类发出GET请求。 MyWebServer不记录请求,因此我假设请求格式不正确。

 public void MakeRequest()
    {
        int port = 80;
        IPHostEntry host = Dns.GetHostEntry("192.168.1.152");
        IPEndPoint endPoint = new IPEndPoint(host.AddressList[0], 80);

        using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            socket.Connect(endPoint);

            using (NetworkStream ns = new NetworkStream(socket))
            {
                byte[] bytes = System.Text.Encoding.UTF8.GetBytes(@"GET /MyWebServer HTTP/1.1\r\n");
                ns.Write(bytes, 0, bytes.Length);
            }
        }
    }

1 个答案:

答案 0 :(得分:2)

首先,您不需要将Dns.GetHostEntry()用于IP地址,只需要使用主机名:

IPEndPoint endPoint = new IPEndPoint("192.168.1.152", 80);

其次,您的请求格式不正确。您缺少Host标头(HTTP 1.1中要求),并且在请求结束时您遗漏了最终\r\n

byte[] bytes = System.Text.Encoding.UTF8.GetBytes(@"GET /MyWebServer HTTP/1.1\r\nHost: 192.168.1.152\r\n\r\n");

话虽如此,您确实应该使用HttpWebRequestHttpClient而不是直接使用NetworkStream,例如:

using (WebRequest Request = new WebRequest.Create("http://192.168.1.152/MyWebServer"))
{
    WebResponse Response = Request.GetResponse();
    // use Response as needed...
}

using (HttpClient Client = new HttpClient())
{
    client.BaseAddress = new Uri("http://192.168.1.152/");
    HttpResponseMessage Response = await Client.GetAsync("MyWebServer");
    // use Response as needed...
}