How to create an HTTP API using Java without any web frameworks like Spring, Java EE?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With