Howto create easily a Local HTTP Server using Java

In Java, creating a local HTTP server is very easy.

You can add more context to handle more HTTP paths.

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

public class LocalHttpServer {

public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(Integer.parseInt(args[0])), 0);
server.createContext("/localServer", new LocalHttpHandler());
server.setExecutor(null);
server.start();
}

static class LocalHttpHandler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
String response = "Welcome to Local Http Server";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s