simple HTTP server in Java using only Java SE API

前端 未结 17 1906
无人共我
无人共我 2020-11-22 13:28

Is there a way to create a very basic HTTP server (supporting only GET/POST) in Java using just the Java SE API, without writing code to manually parse HTTP requests and man

17条回答
  •  没有蜡笔的小新
    2020-11-22 14:12

    All the above answers details about Single main threaded Request Handler.

    setting:

     server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
    

    Allows multiple request serving via multiple threads using executor service.

    So the end code will be something like below:

    import java.io.IOException;
    import java.io.OutputStream;
    import java.net.InetSocketAddress;
    import com.sun.net.httpserver.HttpExchange;
    import com.sun.net.httpserver.HttpHandler;
    import com.sun.net.httpserver.HttpServer;
    public class App {
        public static void main(String[] args) throws Exception {
            HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
            server.createContext("/test", new MyHandler());
            //Thread control is given to executor service.
            server.setExecutor(java.util.concurrent.Executors.newCachedThreadPool());
            server.start();
        }
        static class MyHandler implements HttpHandler {
            @Override
            public void handle(HttpExchange t) throws IOException {
                String response = "This is the response";
                long threadId = Thread.currentThread().getId();
                System.out.println("I am thread " + threadId );
                response = response + "Thread Id = "+threadId;
                t.sendResponseHeaders(200, response.length());
                OutputStream os = t.getResponseBody();
                os.write(response.getBytes());
                os.close();
            }
        }
    }
    

提交回复
热议问题