Skip to content

tom-heidenreich/Java-HttpServer

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

68 Commits
 
 
 
 
 
 

Repository files navigation

Java-HttpServer

Create Server

HttpServer server = new HttpServer(80);
HttpServer server = new HttpServer(new InetSocketAddress(80), 0);

Set Executor

  • Single Thread

server.setExecutor(Executors.newSingleThreadExecutor());
  • Fixed Threads

server.setExecutor(Executors.newFixedThreadPool(10));
  • Multi Threads

This is the default executor.

server.setExecutor(Executors.newCachedThreadPool());

Set Handler

  • Handle GET requests

server.get("/home", (req, res) -> {

});
  • Handle POST requests

server.post("/home", (req, res) -> {

});
  • Handle any method

server.handle("*", "/home", (req, res) -> {

});
  • Alternative

server.addHandler("/home", (req, res) -> {

});

Request

Headers

req.getRequestHeader("Connection");

URI

req.getRequestURI();

Method

req.getRequestMethod();

Remote Address

req.getRemoteAddress();

Cookies

Cookie[] cookies = req.getCookies();
Cookie cookie = req.getCookie("name");

Params

String param = req.getParam("name");

Body

String body = req.getRequestBody();
byte[] body = req.getRequestBodyBytes();

Response

Head

res.status(200)
res.writeHead(200, (head) -> {
    head.setHeader("Content-Type", "text/plain");
});

Body

res.send("Hello World!");

Or with status code

res.send(200, "Hello World!");

You can also use write. This will not end the response and you can send bytes

res.write("Hello World!");

End

Using send will already end the response.

res.end();

Start

server.start(); 

Or

server.start(()->{
    System.out.println("Server started!");
});