culgjq
Last Updated: February 25, 2016
·
1.372K
· dr_xaos

groovy (java) simple http server with basic auth

Run a simple web server from groovy:

def handler = new ScriptHttpHandler()
def server = HttpServer.create(new InetSocketAddress(8080), 0)
HttpContext context = server.createContext("/", handler)
context.setAuthenticator(new BasicAuthAuthenticator())
server.start()

Request handler:

class ScriptHttpHandler implements HttpHandler {

    @Override
    void handle(HttpExchange exchange) {
        exchange.responseHeaders.set("Content-Type", "text/plain")
        exchange.sendResponseHeaders(200, 0)
        exchange.responseBody.withStream { OutputStream stream ->
            doExecute(exchange.requestBody, stream)
        }
    }

    protected void doExecute(InputStream input, OutputStream output) {
        ....
    }
}

Authentication:

class BasicAuthAuthenticator extends BasicAuthenticator {

    RemoteControlAuthenticator() {
        super("enter password")
    }

    @Override
    boolean checkCredentials(String user, String pwd) {
        return user.equals("user") && pwd.equals("password")
    }
}
Say Thanks
Respond