Reputation: 3156
I am trying to make a GET request using the NetworkStream class. MyWebServer does not log the request so I am assumming that request is not formatted properly.
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);
}
}
}
Upvotes: 0
Views: 1003
Reputation: 596096
First, you don't need to use Dns.GetHostEntry()
for IP addresses, only hostnames:
IPEndPoint endPoint = new IPEndPoint("192.168.1.152", 80);
Second, your request is not formatted correctly. You are missing the Host
header (required in HTTP 1.1), and you are missing a final \r\n
at the end of the request:
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(@"GET /MyWebServer HTTP/1.1\r\nHost: 192.168.1.152\r\n\r\n");
That being said, you really should be using HttpWebRequest
or HttpClient
instead of using NetworkStream
directly, eg:
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...
}
Upvotes: 2