The package com.sun.net.httpserver provides Http server API, which can be used to build embedded HTTP servers. To get started with this API, we need to get familiar with the following classes:
Example
This is a very simple example to create the HttpServer:
public class BasicHttpServerExample {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
HttpContext context = server.createContext("/");
context.setHandler(BasicHttpServerExample::handleRequest);
server.start();
}
private static void handleRequest(HttpExchange exchange) throws IOException {
String response = "Hi there!";
exchange.sendResponseHeaders(200, response.getBytes().length);//response code and length
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
Output
Running the above main class and accessing the application in the browser:
Accessing Request Information
public class BasicHttpServerExample2 {
public static void main(String[] args) throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
HttpContext context = server.createContext("/example");
context.setHandler(BasicHttpServerExample2::handleRequest);
server.start();
}
private static void handleRequest(HttpExchange exchange) throws IOException {
URI requestURI = exchange.getRequestURI();
printRequestInfo(exchange);
String response = "This is the response at " + requestURI;
exchange.sendResponseHeaders(200, response.getBytes().length);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes());
os.close();
}
private static void printRequestInfo(HttpExchange exchange) {
System.out.println("-- headers --");
Headers requestHeaders = exchange.getRequestHeaders();
requestHeaders.entrySet().forEach(System.out::println);
System.out.println("-- principle --");
HttpPrincipal principal = exchange.getPrincipal();
System.out.println(principal);
System.out.println("-- HTTP method --");
String requestMethod = exchange.getRequestMethod();
System.out.println(requestMethod);
System.out.println("-- query --");
URI requestURI = exchange.getRequestURI();
String query = requestURI.getQuery();
System.out.println(query);
}
}
Output
On the server console:
-- headers --
Accept-encoding=[gzip, deflate, br]
Cookie=[Idea-d72f48cc=a1722887-bfad-47cd-b8b3-df88f97951e3]
Accept=[text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8]
Connection=[keep-alive]
Host=[localhost:8500]
User-agent=[Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.170 Safari/537.36]
Accept-language=[en-US,en;q=0.9]
Upgrade-insecure-requests=[1]
-- principle --
null
-- HTTP method --
GET
-- query --
x=1&y=2
Example ProjectDependencies and Technologies Used:
|