• Home
  • About

Snippet IT

IT News, Programming, Internet and Blogging

  • Programming and Scripting
  • Tips and Tricks
  • Software and Hardware
  • New and Happening
You are here: Home / Programming and Scripting / Java: How To Create A Simple Web Server Using HttpServer

Java: How To Create A Simple Web Server Using HttpServer

January 8, 2013 by Sze Hau Leave a Comment

To program a web or HTTP server from nothing could be very difficult. It’s gonna to take you to write thousands of source instructions. The HTTP protocol it self is pretty to understand but it complicated to implement them in programming language. It involves a lot of parsing and need a lot of understanding how the HTTP requests and HTTP responses work together.

In Java SDK, you can use the HttpServer class in com.sun.net.httpserver.HttpServer package. It is pretty simple to use HttpServer to create a simple web server, what you need to do is to implement a HttpHandler for a specific URL/context.

Below is a sample of simple HTTP server that send files sit on the web server to client when user request the file via web browser.

import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import com.sun.net.httpserver.*;

public class TimeServer
{
    private static int SERVER_PORT = 3000;

    private class FileDownloadHandler
	implements HttpHandler
    {
	public void
	handle (
	    HttpExchange	httpExc)
	    throws IOException 
	{
	    String		filename;
	    String		contentType;
	    OutputStream	out;
	    long		rspLen;
	    int			len;
	    byte[]		buffer;
	    File		file;
	    FileInputStream	in;

	    filename = httpExc.getRequestURI ().getPath ();
	    if (filename == null || filename.isEmpty ())
		filename = "TimeClient.html";
	    if (filename.startsWith ("/"))
		filename = filename.substring (1);

	    file = new File (filename);
	    if (!file.isFile ()) {
		sendResponse (httpExc, 404, 
		    "Not found: " + filename + "");
		System.err.println ("Not found: " + filename);
	    	return;
	    }

	    in = null;
	    buffer = new byte[4096];
	    out = httpExc.getResponseBody ();
	    rspLen = file.length ();
	    httpExc.sendResponseHeaders (200, rspLen);
	    try {
	    	in = new FileInputStream (file);
	    } catch (IOException e) {
		sendResponse (httpExc, 500, 
		    "Error reading file: " + 
		    	filename + "");
		System.err.println ("Error reading file: " + filename);
	    	return;
	    }
	    try {
		while ((len = in.read(buffer)) != -1)
		    out.write (buffer, 0, len);
	    } catch (IOException e) {
		sendResponse (httpExc, 500, 
		    "Error writing file: " + 
		    	filename + "");
		System.err.println ("Error writing file: " + filename);
	    }
	    try {
	    	in.close ();
	    } catch (IOException e) {
		// DO NOTHING
	    }
	    try {
	    	out.close ();
	    } catch (IOException e) {
		// DO NOTHING
	    }
	}
    }

    public void
    sendResponse (
	HttpExchange		httpExc,
	int 			responseCode,	// Response code
	String 			responseBody)	// Response body
    	throws IOException
    {
	byte[]			data;		// Data
	OutputStream		out;		// Output stream

	data = responseBody.getBytes ();
	httpExc.sendResponseHeaders (responseCode, data.length);
	out = httpExc.getResponseBody ();
	out.write (data, 0, data.length);
	out.close ();
    }

    public void
    main ()
    	throws IOException
    {
	HttpServer		server;

	// Create and start the http server instance

	server = HttpServer.create (new InetSocketAddress(SERVER_PORT), 0);
	server.createContext ("/", new FileDownloadHandler());
	server.setExecutor (null);
	server.start ();
    }

    public static void 
    main (
	String[]		args)
    throws Exception 
    {
	(new WebServer()).main ();
    }
}

The example above is just a very simple web server that allow user to download files. If you need a more comprehensive one, you may want to look into the packages in J2EE (Servlet and JSP).

More from my site

  • Java: How To Select Top N Objects From A ListJava: How To Select Top N Objects From A List
  • Java: Format Integer Into Fixed Width StringJava: Format Integer Into Fixed Width String
  • Java: Continuously Read Data From FileChannel Without MappedByteBufferJava: Continuously Read Data From FileChannel Without MappedByteBuffer
  • Java: Loading Large Data into JTable or JListJava: Loading Large Data into JTable or JList
  • Java: Format Long Integer Into Hexadecimal StringJava: Format Long Integer Into Hexadecimal String
  • Java: Stop A Thread CorrectlyJava: Stop A Thread Correctly

Filed Under: Programming and Scripting, Tips and Tricks Tagged With: how to, HTTP, Java, web server

About Sze Hau

Geek. Love programming. Coffee addicted. Married with two children. Working towards financial freedom.

Leave a Reply Cancel reply

Advertisement

  • Facebook
  • Google+
  • Instagram
  • Twitter

Email News Letter

Sign up to receive updates daily and to hear what's going on with us

Software and Hardware

MD5 and SHA1 Checksum Using Windows

July 5, 2017 By Sze Hau Leave a Comment

Blog Network

  • Personal Fincance Personal Finance – Personal Money Tips, Stock Investment, Small Business and Make Money Online
  • szehau's weblog Life, Internet, Software, Gadgets, Programming and Investments

Snippet IT

This is the place where I want to share anything about information technology.

Search

Recent

  • MD5 and SHA1 Checksum Using Windows
  • MD5 and SHA1 Checksum Using Linux
  • Java: Unlimited Strength Jurisdiction Policy
  • WordPress: How To Change Admin Username
  • Linux: How To Compress And Decompress Folders And Files

Tags

Adsense advertisement advertising apache blog blogging tips C# EGPC error estimation format format Integer Gmail Google Google Adsense Google Chrome Google Search Engine Google search result how to HTTP internet marketing Java JavaScript Linux money password performance PHP programming search engine optimization secure security short URL SQL static constructor String tiny URL Tips and Tricks twitter video Windows Vista Wordpress wordpress plugin wordpress theme Youtube

Copyright © 2025 · Magazine Pro Theme on Genesis Framework · WordPress · Log in