How to configure com.sun.net.httpserver to remove wildcard binding?

67 views Asked by At

I am using the com.sun.net.httpserver.HttpServer to expose a REST API in a kubernates microservice. Till now it was with wildcard binding. I need to remove the wildcard binding to bind this to its local IP

I am using the com.sun.net.httpserver.HttpServer to expose a REST API in a kubernates microservice. Till now i had been using

httpServer = JdkHttpServerFactory.createHttpServer("http://localhost:" + port + "/"", resourceConfig, false); 
httpServer.start();

With this the port would be having a wildcard binding through which anyone can connect.

I have a requirement now to remove the wildcard binding from this port and have modified my code to below

InetAddress localHost = InetAddress.getLoopbackAddress();
InetSocketAddress sockAddr = new InetSocketAddress(localHost, port);
httpServer = com.sun.net.httpserver.HttpServer.create();
httpServer.bind(sockAddr,5);
httpServer.start();

With the above code, I see that the wildcard binding has got removed ([::ffff:127.0.0.1]:) but the API is not accessible from within the pod or outside.

Edit( Tried this code as well)

InetSocketAddress sockAddr = new InetSocketAddress(localHost, port);
httpServer = com.sun.net.httpserver.HttpServer.create();
httpServer.bind(sockAddr,5);
httpServer.start();

With the above code netstat shows * binding but Error 404 is not seen. Instead the curl command never comes out.

Can someone please point out the mistake here?

1

There are 1 answers

0
Firok On

You have to call server.createContext method to register your own HTTP request handler and finish the HTTP request by yourself.

For example:

var server = com.sun.net.httpserver.HttpServer.create();
server.createContext("/", exchange -> {
    try(var os = exchange.getResponseBody())
    {
        var buffer = "hello world".getBytes(StandardCharsets.UTF_8);
        exchange.sendResponseHeaders(200, buffer.length);
        os.write(buffer);
        os.flush();
    }
});

In addition, if you want to request that server in any web broswer, you will have to handle response headers by yourself (via calling exchange.getResponseHeaders().add("xxx", "xxx")) and handle preflighted request to solve CORS policy problems.