HTTP Server in your Jar

I recently had the need to be able to access a couple of files from a number of computers and didn’t want to setup network shares and things.  These were a simple text files, that I was logging information into. However I was going to be moving around a number of systems and needed to be able to check on those logs occasionally.  Obviously I didn’t want to install a full blown web-server for a couple of hours of work, to access those files.  Why not create my own HTTP server?  Well it’s much easier than it used to be, which even then it was amazingly easy, but in today’s java world it’s even easier.  In fact I got carried away a little bit on it, and made it a bit fancier than it needed to be.

WARNING: This is NOT a robust, secure HTTP Server, this is a simple HTTP Server, for when you need one, without the hassle of installing one.  If you need robust, and secure, then go install Apache HTTP, Apache Tomcat or something else!

First step you need to use com.sun.net.httpserver.HttpServer.  The main step you need is to create a couple of methods:

  • main() to use to start from the command line easily and to be able to restart if necessary.
  • start() to use to setup the properties for the HttpServer.

Next you’ll want to create a ThreadPoolExecutor to handle the incoming requests.  That’s basically it.  I have included the entire file below along with the properties files for configuration.  I trust that you can follow along!

To control the settings, I use a property file.  Here is my sample:

Next thing is you need some handlers, and one of my next posts will discuss those!

Leave a Reply

Your email address will not be published. Required fields are marked *