httpserver example java

Solutions on MaxInterview for httpserver example java by the best coders in the world

showing results for - "httpserver example java"
Yael
25 Jun 2019
1public class BasicHttpServerExample {
2
3  public static void main(String[] args) throws IOException {
4      HttpServer server = HttpServer.create(new InetSocketAddress(8500), 0);
5      HttpContext context = server.createContext("/");
6      context.setHandler(BasicHttpServerExample::handleRequest);
7      server.start();
8  }
9
10  private static void handleRequest(HttpExchange exchange) throws IOException {
11      String response = "Hi there!";
12      exchange.sendResponseHeaders(200, response.getBytes().length);//response code and length
13      OutputStream os = exchange.getResponseBody();
14      os.write(response.getBytes());
15      os.close();
16  }
17}