javacodex.com
Java Examples
Java Examples
memu home questions

Simple HTTP Server

The class HttpServer implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address.

The class HttpHandler is a handler which is invoked to process HTTP exchanges. Each HTTP exchange is handled by one of these handlers.

Source: (MyHTTPServer.java)

import java.io.*;
import java.net.*;
import com.sun.net.httpserver.*;
 
public class MyHTTPServer {
 
   public static void main(String[] args) throws Exception {
      HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
      server.createContext("/hello", new MyHandler());
      server.setExecutor(null);
      server.start();
      System.out.println("Server is listening on port 8080" );
   }
 
   static class MyHandler implements HttpHandler {
      public void handle(HttpExchange t) throws IOException {
         String response = "Hello from MyHTTPServer.....";
         t.sendResponseHeaders(200, response.length());
         OutputStream os = t.getResponseBody();
         os.write(response.getBytes());
         os.close();
      }
   }
}
 

Output:

$ java MyHTTPServer &
Server is listening on port 8080


$ wget http://localhost:8080/hello -q -O -
Hello from MyHTTPServer.....


Contact: javacodex@yahoo.com