Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/319.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何使用NetworkStream类发出GET请求?_C#_.net_Sockets_Http - Fatal编程技术网

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

C# 如何使用NetworkStream类发出GET请求?,c#,.net,sockets,http,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)

我正在尝试使用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);
            }
        }
    }

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

IPEndPoint endPoint = new IPEndPoint("192.168.1.152", 80);
其次,您的请求格式不正确。您缺少
主机
头(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");
也就是说,您确实应该直接使用或代替
NetworkStream
,例如:

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


我会试试你推荐的,明天再汇报。我不使用WebRequest的原因是我使用微框架运行它,所以我想要一个非常小的脚印。谢谢
using (HttpClient Client = new HttpClient())
{
    client.BaseAddress = new Uri("http://192.168.1.152/");
    HttpResponseMessage Response = await Client.GetAsync("MyWebServer");
    // use Response as needed...
}