Java 如何實現(xiàn)一個http服務器
在Java中可以使用HttpServer類來實現(xiàn)Http服務器,該類位于com.sun.net包下(rt.jar)。實現(xiàn)代碼如下:
主程序類
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 { //創(chuàng)建一個HttpServer實例,并綁定到指定的IP地址和端口號 HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0); //創(chuàng)建一個HttpContext,將路徑為/myserver請求映射到MyHttpHandler處理器 httpServer.createContext("/myserver", new MyHttpHandler()); //設置服務器的線程池對象 httpServer.setExecutor(Executors.newFixedThreadPool(10)); //啟動服務器 httpServer.start(); } }
HttpServer:HttpServer主要是通過帶參的create方法來創(chuàng)建,第一個參數(shù)InetSocketAddress表示綁定的ip地址和端口號。第二個參數(shù)為int類型,表示允許排隊的最大TCP連接數(shù),如果該值小于或等于零,則使用系統(tǒng)默認值。
createContext:可以調(diào)用多次,表示將指定的url路徑綁定到指定的HttpHandler處理器對象上,服務器接收到的所有路徑請求都將通過調(diào)用給定的處理程序?qū)ο髞硖幚怼?/p>
setExecutor:設置服務器的線程池對象,不設置或者設為null則表示使用start方法創(chuàng)建的線程。
HttpHandler實現(xiàn)
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("請求參數(shù):").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/>")); } /** * 獲取請求參數(shù) * @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方法之前調(diào)用! httpExchange.sendResponseHeaders(200, responseContentByte.length); OutputStream out = httpExchange.getResponseBody(); out.write(responseContentByte); out.flush(); out.close(); } }
運行HttpServerStarter,在瀏覽器中訪問如下:
以上就是Java 如何實現(xiàn)一個http服務器的詳細內(nèi)容,更多關(guān)于Java 實現(xiàn)http服務器的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
JAVA Iterator 轉(zhuǎn)成 List 的操作
這篇文章主要介紹了JAVA Iterator 轉(zhuǎn)成 List 的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12RxJava中map和flatMap的用法區(qū)別源碼解析
這篇文章主要為大家介紹了RxJava中map和flatMap的用法區(qū)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09Java實現(xiàn)網(wǎng)絡數(shù)據(jù)提取所需知識點
這篇文章主要介紹了Java實現(xiàn)網(wǎng)絡數(shù)據(jù)提取所需知識點,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07搜索一文入門ElasticSearch(節(jié)點 分片 CRUD 倒排索引 分詞)
這篇文章主要為大家介紹了搜索一文入門ElasticSearch(節(jié)點 分片 CRUD 倒排索引 分詞)的基礎(chǔ)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-03-03