@Viorel I am doing pretty much the same with TcpListener. I did write up a test using HttpListener but it has to be run in admin mode to work. Since I can not do that I have coded up a test with TcpListener. Unless you know how to get HttpListener to work without admin mode? So now, I have the same question. How to properly parse the request with the same functionality as HttpListener. You're right though.. it is easier with HttpListener!
C# TCPListener Get POST request data
I have this simple TCPListener HTTP request:
TcpListener tcpListener = new TcpListener(IPAddress.Loopback, 44394);
tcpListener.Start();
while (true)
{
Console.WriteLine("Listening...");
TcpClient client = tcpListener.AcceptTcpClient();
using (NetworkStream stream = client.GetStream())
{
byte[] requestBytes = new byte[100000];
int readBytes = stream.Read(requestBytes, 0, requestBytes.Length);
var requestResult = Encoding.UTF8.GetString(requestBytes, 0, readBytes);
Console.WriteLine("------------Begin of Request------------");
Console.WriteLine(requestResult);
Console.WriteLine("------------End of Request------------");
Console.Write("\n\n\n");
TextReader fileReader = new StreamReader(websitePath);
string html = fileReader.ReadToEnd();
StreamWriter writer = new StreamWriter(stream);
writer.Write("HTTP/1.1 200 Success");
writer.Write(Environment.NewLine);
writer.Write($"Content-Type: text/html");
writer.Write(Environment.NewLine);
writer.Write("Content-Length: " + html.Length);
writer.Write(Environment.NewLine);
writer.Write(Environment.NewLine);
writer.Write(html);
writer.Flush();
}
}
}
And this index.html:
<h1>Hello world</h1>
<form action="" method=POST>
<input id=data type=text>
<input id=submit type = submit>
</form>
How to get in the c# the content of the input with the id data as a POST request?
2 answers
Sort by: Most helpful
-
-
Bruce (SqlWork.com) 56,686 Reputation points
2024-01-17T17:05:21.1+00:00 the browser posts a form with the content-type of "application/x-www-form-urlencoded" or "multipart/form-data" (used with input type="file"), for url encoded form the body is a collection of name / value pairs. the name/value is separated with an "=", and the pairs are separated with a "&". both the name and value are url encoded. the name matches the name attribute of the form field, the value its value.
only enabled form fields with a name are included in the post data. in addition a radio or checkbox is only included if it is checked. the clicked button will be included if it has a name.
in your sample form, none of the form fields have a name attribute, so the post data will be empty.
for example the form:
<form method="post"> <input name="a" value="1"> <input name="a" value="2"> <input name="b" value="3"> <input name="c" type="submit" value="click"> </form>
will post the data (if button clicked)
a=1&a=2&b=3&c=click
note: the post data follows the blank line after the headers