Simple java http server, from java


/ Published in: Java
Save to your folder(s)

A simple http server, from java JDK.


Copy this code and paste it in your HTML
  1. package com.example;
  2.  
  3. import java.io.IOException;
  4. import java.io.OutputStream;
  5. import java.net.InetSocketAddress;
  6.  
  7. import com.sun.net.httpserver.HttpExchange;
  8. import com.sun.net.httpserver.HttpHandler;
  9. import com.sun.net.httpserver.HttpServer;
  10.  
  11. public class Test {
  12.  
  13. public static void main(String[] args) throws Exception {
  14. HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
  15. server.createContext("/test", new MyHandler());
  16. server.setExecutor(null); // creates a default executor
  17. server.start();
  18. }
  19.  
  20. static class MyHandler implements HttpHandler {
  21. public void handle(HttpExchange t) throws IOException {
  22. String response = "This is the response";
  23. t.sendResponseHeaders(200, response.length());
  24. OutputStream os = t.getResponseBody();
  25. os.write(response.getBytes());
  26. os.close();
  27. }
  28. }
  29.  
  30. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.