Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create HTTP API using Java without any web framework like Spring, Java EE? [closed]

Tags:

java

rest

http

How to create an HTTP API using Java without any web frameworks like Spring, Java EE?

like image 423
saravanan Avatar asked Sep 07 '25 07:09

saravanan


1 Answers

The basics of HTTP are fairly simple. Open a ServerSocket to listen for incoming requests. When a connection is made, start a new thread and send the response. That could look like,

public static void main(String[] args) {
    try {
        ServerSocket ss = ServerSocketFactory.getDefault().createServerSocket(8080, 10);
        StringBuilder body = new StringBuilder();
        body.append("<html><body><h1>Hello, World!</h1></body></html>");
        while (true) {
            Socket s = ss.accept();
            Thread t = new Thread(new HttpReply(s, body));
            t.start();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Then to actually send the response you get an OutputStream from the Socket and write the required HTTP headers and then the body. Like,

class HttpReply implements Runnable {
    private Socket s;
    private StringBuilder body;

    private HttpReply(Socket s, StringBuilder body) {
        this.s = s;
        this.body = body;
    }

    public void run() {
        try {
            PrintStream ps = new PrintStream(s.getOutputStream());
            ps.println("HTTP/1.1 200 OK");
            ps.println("Date: Mon, 27 Jul 2009 12:28:53 GMT");
            ps.println("Server: Java");
            ps.println("Last-Modified: Wed, 22 Jul 2009 19:15:56 GMT");
            ps.println("Content-Length: " + body.length());
            ps.println("Content-Type: text/html");
            ps.println("Connection: Closed");
            ps.println();
            ps.println(body);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Which will listen on port 8080 of your machine for requests and reply with a basic hello world web page.

Hello World Web Page

like image 164
Elliott Frisch Avatar answered Sep 10 '25 11:09

Elliott Frisch