Reputation: 392
I am currently working on a local http server written in C#. At this point I am not yet processing post data, but only distinguish between get and post request. In both cases, of course, a 200 should be answered. While testing the server, I noticed that if I send an empty post request, it is answered by the server with a 200 and an html page just like a get request without any problems. However, if there are images attached to the post request, as in my example, the connection to the server fails immediately.
I handle a client connection as follows. I know it's not ideal to store the received bytes in a string, but for testing purposes I haven't seen any problems with it.
private void HandleClient(TcpClient client)
{
Byte[] bytes;
String requestData = "";
NetworkStream ns = client.GetStream();
if (client.ReceiveBufferSize > 0)
{
bytes = new byte[client.ReceiveBufferSize];
ns.Read(bytes, 0, client.ReceiveBufferSize);
requestData = Encoding.ASCII.GetString(bytes);
}
// Get Request out of message
Request request = Request.GetRequest(requestData);
// Create Response
Response response = Response.From(request);
response.Post(client.GetStream());
}
And here is the method I use to determine what type of request it is.
public static Request GetRequest(String request)
{
//return if request is null
if(String.IsNullOrEmpty(request))
{
return null;
}
//Split Request to get tokens - split by spaces
String[] tokens = request.Split(' ');
String type = tokens[0];
String url = tokens[1];
String host = tokens[4];
return new Request(type, url, host);
}
Surely it must be possible to read only the headers from a get as well as post request and then still give a 200 response. Is there a rule of behavior for an http server on how it should handle post-request data?
Upvotes: 0
Views: 810
Reputation: 392
The answer to my question was quite simple in the end. The input stream of a request must be read completely before the server can respond to the request. In my case it was so, that I only read the header of the request to know if it is a Post or Get request, therefore the server could not respond to the request in case of an attached image, because the input stream was not read completely.
Upvotes: 1