In this post, we will learn about add rest service in core java application
We are in spring boot world, where exposing a http endpoint is much easier, but when it comes to a standalone java application we will get confused
Java has a feature to expose Http endpoint from a standalone application.
Using import com.sun.net.httpserver.HttpExchange;
In below example, we are exposing an Http endpoint on port number 8080 with endpoint /health
Example
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public class HttpServerExample {
public static void main(String[] args) throws Exception {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
server.createContext("/health", new Handler());
server.setExecutor(null);
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
static class Handler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "Up & Running";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
}
Output
Up & Running
If you are not found com.net.sun.http package in your eclipse follow this URL https://beginnersbug.com/com-sun-net-httpserver-httpexchange-not-found-in-eclipse