views:

45

answers:

1

I am writing a server-side program. I created a HttpListener to listen for incoming requests. How can I find out what kind of data is being sent in? E.g. is it a text, image, pdf, word?

Pls correct my code below if it is wrong. I'm really new to this and my understanding of the HTTP concepts may be wrong. Thanks.

main()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://192.168.1.2/");
listener.Start();

while (true) //Keep on listening
{
context = listener.GetContext();
HttpListenerRequest request = context.Request;

//Do I get the request stream here, and do something with the stream to find out what data format is being sent?
Stream requestStream = request.InputStream;
}

}
+3  A: 

The only easy way to know what type of data is being sent is by looking at the request's Content-Type header (exposed via the ContentType property), which should contain the MIME type of the content:

switch(request.ContentType)
{
    case "image/png":
    case "image/jpeg":
    case "image/bmp":
    case "image/gif":
    case "image/tiff":
        // OK, this is an image
        ...
        break;
    default:
        // Something else
        ...
        break;
}

Note that this approach won't always work, because the client could send a request without specifying the Content-Type header, or send data that doesn't match the header...

Thomas Levesque