Java 如何實現(xiàn)一個http服務(wù)器
在Java中可以使用HttpServer類來實現(xiàn)Http服務(wù)器,該類位于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()); //設(shè)置服務(wù)器的線程池對象 httpServer.setExecutor(Executors.newFixedThreadPool(10)); //啟動服務(wù)器 httpServer.start(); }}
HttpServer:HttpServer主要是通過帶參的create方法來創(chuàng)建,第一個參數(shù)InetSocketAddress表示綁定的ip地址和端口號。第二個參數(shù)為int類型,表示允許排隊的最大TCP連接數(shù),如果該值小于或等于零,則使用系統(tǒng)默認值。
createContext:可以調(diào)用多次,表示將指定的url路徑綁定到指定的HttpHandler處理器對象上,服務(wù)器接收到的所有路徑請求都將通過調(diào)用給定的處理程序?qū)ο髞硖幚怼?/p>
setExecutor:設(shè)置服務(wù)器的線程池對象,不設(shè)置或者設(shè)為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; } /** * 處理響應(yīng) * @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'); //設(shè)置響應(yīng)頭,必須在sendResponseHeaders方法之前設(shè)置! httpExchange.getResponseHeaders().add('Content-Type:', 'text/html;charset=utf-8'); //設(shè)置響應(yīng)碼和響應(yīng)體長度,必須在getResponseBody方法之前調(diào)用! httpExchange.sendResponseHeaders(200, responseContentByte.length); OutputStream out = httpExchange.getResponseBody(); out.write(responseContentByte); out.flush(); out.close(); }}
運行HttpServerStarter,在瀏覽器中訪問如下:
以上就是Java 如何實現(xiàn)一個http服務(wù)器的詳細內(nèi)容,更多關(guān)于Java 實現(xiàn)http服務(wù)器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. XHTML 1.0:標(biāo)記新的開端2. 基于javaweb+jsp實現(xiàn)學(xué)生宿舍管理系統(tǒng)3. 多級聯(lián)動下拉選擇框,動態(tài)獲取下一級4. 最新JavaScript判斷是否是360瀏覽器方法5. PHP擴展之URL編碼、解碼及解析——URLs6. 教你使用idea搭建ssm詳細教程(Spring+Spring Mvc+Mybatis)7. js判斷兩個數(shù)組是否存在相同元素的四種方法8. 在vue中獲取wangeditor的html和text的操作9. python 實現(xiàn)的車牌識別項目10. PHP基礎(chǔ)之?dāng)?shù)據(jù)類型6——對象(Object)
