Java 如何實(shí)現(xiàn)一個(gè)http服務(wù)器
在Java中可以使用HttpServer類來實(shí)現(xiàn)Http服務(wù)器,該類位于com.sun.net包下(rt.jar)。實(shí)現(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)建一個(gè)HttpServer實(shí)例,并綁定到指定的IP地址和端口號(hào) HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0); //創(chuàng)建一個(gè)HttpContext,將路徑為/myserver請(qǐng)求映射到MyHttpHandler處理器 httpServer.createContext("/myserver", new MyHttpHandler()); //設(shè)置服務(wù)器的線程池對(duì)象 httpServer.setExecutor(Executors.newFixedThreadPool(10)); //啟動(dòng)服務(wù)器 httpServer.start(); } }
HttpServer:HttpServer主要是通過帶參的create方法來創(chuàng)建,第一個(gè)參數(shù)InetSocketAddress表示綁定的ip地址和端口號(hào)。第二個(gè)參數(shù)為int類型,表示允許排隊(duì)的最大TCP連接數(shù),如果該值小于或等于零,則使用系統(tǒng)默認(rèn)值。
createContext:可以調(diào)用多次,表示將指定的url路徑綁定到指定的HttpHandler處理器對(duì)象上,服務(wù)器接收到的所有路徑請(qǐng)求都將通過調(diào)用給定的處理程序?qū)ο髞硖幚怼?/p>
setExecutor:設(shè)置服務(wù)器的線程池對(duì)象,不設(shè)置或者設(shè)為null則表示使用start方法創(chuàng)建的線程。
HttpHandler實(shí)現(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路徑請(qǐng)求的處理器類 */ public class MyHttpHandler implements HttpHandler { @Override public void handle(HttpExchange httpExchange) { try { StringBuilder responseText = new StringBuilder(); responseText.append("請(qǐng)求方法:").append(httpExchange.getRequestMethod()).append("<br/>"); responseText.append("請(qǐng)求參數(shù):").append(getRequestParam(httpExchange)).append("<br/>"); responseText.append("請(qǐng)求頭:<br/>").append(getRequestHeader(httpExchange)); handleResponse(httpExchange, responseText.toString()); } catch (Exception ex) { ex.printStackTrace(); } } /** * 獲取請(qǐng)求頭 * @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/>")); } /** * 獲取請(qǐng)求參數(shù) * @param httpExchange * @return * @throws Exception */ private String getRequestParam(HttpExchange httpExchange) throws Exception { String paramStr = ""; if (httpExchange.getRequestMethod().equals("GET")) { //GET請(qǐng)求讀queryString paramStr = httpExchange.getRequestURI().getQuery(); } else { //非GET請(qǐng)求讀請(qǐng)求體 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(); } }
運(yùn)行HttpServerStarter,在瀏覽器中訪問如下:
以上就是Java 如何實(shí)現(xiàn)一個(gè)http服務(wù)器的詳細(xì)內(nèi)容,更多關(guān)于Java 實(shí)現(xiàn)http服務(wù)器的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- java編寫Http服務(wù)器下載工具
- Java使用NioSocket手動(dòng)實(shí)現(xiàn)HTTP服務(wù)器
- java Socket實(shí)現(xiàn)簡單模擬HTTP服務(wù)器
- Java/Android 實(shí)現(xiàn)簡單的HTTP服務(wù)器
- Java模擬實(shí)現(xiàn)HTTP服務(wù)器項(xiàng)目實(shí)戰(zhàn)
- Intellij?IDEA?的maven項(xiàng)目通過Java代碼實(shí)現(xiàn)Jetty的Http服務(wù)器(推薦)
- Java創(chuàng)建非阻塞的HTTP服務(wù)器的實(shí)現(xiàn)
相關(guān)文章
Android中Socket通信的實(shí)現(xiàn)方法概述
這篇文章主要介紹了Android中Socket通信的實(shí)現(xiàn)方法,很有實(shí)用價(jià)值,需要的朋友可以參考下2014-08-08JAVA Iterator 轉(zhuǎn)成 List 的操作
這篇文章主要介紹了JAVA Iterator 轉(zhuǎn)成 List 的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12RxJava中map和flatMap的用法區(qū)別源碼解析
這篇文章主要為大家介紹了RxJava中map和flatMap的用法區(qū)別源碼解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-09-09Java實(shí)現(xiàn)網(wǎng)絡(luò)數(shù)據(jù)提取所需知識(shí)點(diǎn)
這篇文章主要介紹了Java實(shí)現(xiàn)網(wǎng)絡(luò)數(shù)據(jù)提取所需知識(shí)點(diǎn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07搜索一文入門ElasticSearch(節(jié)點(diǎn) 分片 CRUD 倒排索引 分詞)
這篇文章主要為大家介紹了搜索一文入門ElasticSearch(節(jié)點(diǎn) 分片 CRUD 倒排索引 分詞)的基礎(chǔ)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-03-03