使用Java實現簡單的Http服務器

在Java中能夠使用HttpServer類來實現Http服務器,該類位於com.sun.net包下(rt.jar)。實現代碼以下:html

主程序類

package bg.httpserver;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

public class HttpServerStarter {
    public static void main(String[] args) throws IOException {
        //建立一個HttpServer實例,並綁定到指定的IP地址和端口號
        HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0);

        //建立一個HttpContext,將路徑爲/myserver請求映射到MyHttpHandler處理器
        httpServer.createContext("/myserver", new MyHttpHandler());

        //設置服務器的線程池對象
        httpServer.setExecutor(Executors.newFixedThreadPool(10));

        //啓動服務器
        httpServer.start();
    }
}

HttpServer:HttpServer主要是經過帶參的create方法來建立,第一個參數InetSocketAddress表示綁定的ip地址和端口號。第二個參數爲int類型,表示容許排隊的最大TCP鏈接數,若是該值小於或等於零,則使用系統默認值。java

createContext:能夠調用屢次,表示將指定的url路徑綁定到指定的HttpHandler處理器對象上,服務器接收到的全部路徑請求都將經過調用給定的處理程序對象來處理。瀏覽器

setExecutor:設置服務器的線程池對象,不設置或者設爲null則表示使用start方法建立的線程。服務器

HttpHandler實現

package bg.httpserver;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 處理/myserver路徑請求的處理器類
 */
public class MyHttpHandler implements HttpHandler {
    @Override
    public void handle(HttpExchange httpExchange) {
        try {
            StringBuilder responseText = new StringBuilder();
            responseText.append("請求方法:").append(httpExchange.getRequestMethod()).append("<br/>");
            responseText.append("請求參數:").append(getRequestParam(httpExchange)).append("<br/>");
            responseText.append("請求頭:<br/>").append(getRequestHeader(httpExchange));
            handleResponse(httpExchange, responseText.toString());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 獲取請求頭
     * @param httpExchange
     * @return
     */
    private String getRequestHeader(HttpExchange httpExchange) {
        Headers headers = httpExchange.getRequestHeaders();
        return headers.entrySet().stream()
                                .map((Map.Entry<String, List<String>> entry) -> entry.getKey() + ":" + entry.getValue().toString())
                                .collect(Collectors.joining("<br/>"));
    }

    /**
     * 獲取請求參數
     * @param httpExchange
     * @return
     * @throws Exception
     */
    private String getRequestParam(HttpExchange httpExchange) throws Exception {
        String paramStr = "";

        if (httpExchange.getRequestMethod().equals("GET")) {
            //GET請求讀queryString
            paramStr = httpExchange.getRequestURI().getQuery();
        } else {
            //非GET請求讀請求體
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpExchange.getRequestBody(), "utf-8"));
            StringBuilder requestBodyContent = new StringBuilder();
            String line = null;
            while ((line = bufferedReader.readLine()) != null) {
                requestBodyContent.append(line);
            }
            paramStr = requestBodyContent.toString();
        }

        return paramStr;
    }

    /**
     * 處理響應
     * @param httpExchange
     * @param responsetext
     * @throws Exception
     */
    private void handleResponse(HttpExchange httpExchange, String responsetext) throws Exception {
        //生成html
        StringBuilder responseContent = new StringBuilder();
        responseContent.append("<html>")
                .append("<body>")
                .append(responsetext)
                .append("</body>")
                .append("</html>");
        String responseContentStr = responseContent.toString();
        byte[] responseContentByte = responseContentStr.getBytes("utf-8");

        //設置響應頭,必須在sendResponseHeaders方法以前設置!
        httpExchange.getResponseHeaders().add("Content-Type:", "text/html;charset=utf-8");

        //設置響應碼和響應體長度,必須在getResponseBody方法以前調用!
        httpExchange.sendResponseHeaders(200, responseContentByte.length);

        OutputStream out = httpExchange.getResponseBody();
        out.write(responseContentByte);
        out.flush();
        out.close();
    }
}

HttpExchange:用於獲取請求內容以及生成和發送響應。app

運行HttpServerStarter,在瀏覽器中訪問以下:

相關文章
相關標籤/搜索