I was in need of a tiny web server for one of my projects, and I found out that
Java 1.6 actually comes with one!
While I have no idea how well this server performs, it’s perfect for what I was
looking for, as my intention is to use it just for one user. First I decided to implement
a simple file server, and over it I want to define some custom URLs with special
handling. So, now that this part is finished, I think it does make a good base for
future projects… so in case you need it, here you’ve it:
importjava.io.FileInputStream;importjava.io.IOException;importjava.io.OutputStream;importjava.io.File;importjava.net.InetSocketAddress;importjava.net.FileNameMap;importjava.net.URLConnection;importjava.util.concurrent.Executors;importcom.sun.net.httpserver.Headers;importcom.sun.net.httpserver.HttpExchange;importcom.sun.net.httpserver.HttpHandler;importcom.sun.net.httpserver.HttpServer;publicclassFileHandlerimplementsHttpHandler{FileNameMapfileNameMap=URLConnection.getFileNameMap();publicstaticvoidmain(String[]args)throwsIOException{intserverPort=8080;InetSocketAddressaddr=newInetSocketAddress(serverPort);HttpServerserver=HttpServer.create(addr,0);server.createContext("/",newFileHandler());server.setExecutor(Executors.newCachedThreadPool());server.start();System.out.println("Server is listening on port "+serverPort);}publicvoidhandle(HttpExchangeexchange)throwsIOException{StringrequestMethod=exchange.getRequestMethod();StringtargetPath=exchange.getRequestURI().getPath();if(requestMethod.equalsIgnoreCase("GET")){// Here it's a good place to include custom path handling,// like calls to Java functions// Handle paths trying to open index.html// Instead of this, we could show a list of the files in the folderif(targetPath.endsWith("/")){targetPath+="index.html";}// Check if file existsFilefileFolder=newFile(".","htdocs");FiletargetFile=newFile(fileFolder,targetPath.replace('/',File.separatorChar));if(targetFile.exists()&&targetFile.isFile()){// If it exists and it's a file, serve itintbufLen=10000*1024;byte[]buf=newbyte[bufLen];intlen=0;HeadersresponseHeaders=exchange.getResponseHeaders();// Get mime type from the ones defined in [jre_home]/lib/content-types.properties StringmimeType=fileNameMap.getContentTypeFor(targetFile.toURI().toURL().toString());if(mimeType==null){mimeType="application/octet-stream";}responseHeaders.set("Content-Type",mimeType);exchange.sendResponseHeaders(200,targetFile.length());FileInputStreamfileIn=newFileInputStream(targetFile);OutputStreamout=exchange.getResponseBody();while((len=fileIn.read(buf,0,bufLen))!=-1){out.write(buf,0,len);}out.close();fileIn.close();}else{// If it doesn't exist, send errorStringmessage="404 Not Found "+exchange.getRequestURI();exchange.sendResponseHeaders(404,0);OutputStreamout=exchange.getResponseBody();out.write(message.getBytes());out.close();}}}}
It’s very basic, but it has default index, 404 errors and MIME type autodetection.