Create a HTTP Server in Java

Here is a quick tutorial on how to create a local embedded HTTP server in Java to serve JSON data. The whole code in less than 30 lines on Java.

package com.juixe.json.server;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.IOException;
import java.net.InetSocketAddress;

public class JSONServer implements HttpHandler {

    public static void main(String[] args) throws IOException  {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/data", new JSONServer());
        server.setExecutor(null);
        server.start();
    }

    @Override
    public void handle(HttpExchange he) throws IOException {
        String response = "{\"message\": \"Hello, HTTP Client\"}";

        he.getResponseHeaders().set("Content-Type", "application/json;charset=UTF-8");
        he.sendResponseHeaders(200, response.length());
        he.getResponseBody().write(response.getBytes());
        he.close();
    }
}

The HttpServer and HttpHandler classes are part of the JRE, so no additional libraries are required. Java also includes a HttpsServer which supports SSL. In the HttpHandler, you can return any data but for this example we are returning a simple JSON response.


Leave a Reply