实现一个简单Http服务器

com.sun.net.httpserver 这个工具包,提供了一些原始的工具

Java Doc 对com.sun.net.httpserver的说明:

This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number and listens for incoming TCP connections from clients on this address. The sub-class HttpsServer implements a server which handles HTTPS requests.

创建httpContext,实现地址的HttpHandler

com.sun.net.httpserver.HttpHandler

A handler which is invoked to process HTTP exchanges. Each HTTP exchange is handled by one of these handlers.

一个简单的例子

在写下面的例子的过程中,让我觉得跟早期tomcat 4.0的处理http的逻辑有点像,写的过程中有点亲切感。只不过tomcat 4.0的代码用的是原始java.net包的Socket和ServerSocket来处理网络通信。而com.sun.net.httpserver进行了一定的封装,简化了实现逻辑。

public class HttpServerTest {
    public static void main(String[] args) {
        run(args);
    }

    public static void run(String[] args) {
        try {
            String url = "localhost";
            int port = 8080;
            HttpServer httpServer = HttpServer.create(new InetSocketAddress(url, port), 0);
            httpServer.createContext("/index", new CustomHttpHandler());
            httpServer.setExecutor(Executors.newFixedThreadPool(10));
            httpServer.start();
            log.info("http server start on port:{} .", port);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static class CustomHttpHandler implements HttpHandler {

        @Override
        public void handle(HttpExchange httpExchange) throws IOException {

            String requestParamValue = null;

            if ("get".equalsIgnoreCase(httpExchange.getRequestMethod())) {
                requestParamValue = handleGetRequest(httpExchange);
            } else if ("post".equals(httpExchange.getRequestMethod())) {
                requestParamValue = handlePostRequest(httpExchange);
            }

            handleResponse(httpExchange, requestParamValue);
        }

        private void handleResponse(HttpExchange httpExchange, String requestParamValue) {

            OutputStream outputStream = httpExchange.getResponseBody();
            StringBuilder htmlBuilder = new StringBuilder();

            htmlBuilder.append("<html>").append("<body>").
                    append("<h1>").append("Hello,I Love You!\nrequestParamValue:").append(requestParamValue).append("</h1>").
                    append("</body>").append("</html>");

            String htmlResponse = htmlBuilder.toString();

            try {
                httpExchange.sendResponseHeaders(200, htmlResponse.length());
                outputStream.write(htmlResponse.getBytes());
                outputStream.flush();
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


        }

        private String handleGetRequest(HttpExchange httpExchange) {
            return httpExchange.getRequestURI().toString().split("\\?")[1].split("=")[1];
        }

        private String handlePostRequest(HttpExchange httpExchange) {
            return null;
        }
    }
}

(完)

发表评论

邮箱地址不会被公开。 必填项已用*标注