Nuclear_Man_D

example HTTP server in Java

Feb 13th, 2019
333
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.02 KB | None | 0 0
  1. import java.io.IOException;
  2. import java.io.OutputStream;
  3. import java.net.InetSocketAddress;
  4. import com.sun.net.httpserver.HttpExchange;
  5. import com.sun.net.httpserver.HttpHandler;
  6. import com.sun.net.httpserver.HttpServer;
  7.  
  8. // my simple implementation for an HTTP server in Java.
  9.  
  10. public class MyHTTPServer implements HttpHandler{
  11.     private HttpServer server;
  12.     public MyHTTPServer(int port) throws IOException {
  13.         server = HttpServer.create(new InetSocketAddress(port), 0);
  14.         server.createContext("/", this);
  15.         server.setExecutor(null); // creates a default executor
  16.     }
  17.     public void handle(HttpExchange exchange) throws IOException {
  18.         String path = exchange.getRequestURI().getPath();
  19.         String response = /* put response here! */ "Hello World!  Path = "+path;
  20.         os.write(response.getBytes());
  21.         os.close();
  22.     }
  23.     public void start() {
  24.         server.start();
  25.     }
  26.  
  27.     public static void main(String[] args) throws IOException {
  28.         // this program can execute!
  29.         new MyHTTPServer(8080).start();
  30.     }
  31. }
Advertisement
Add Comment
Please, Sign In to add comment