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地址和端口號 HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 0); //創(chuàng)建一個(gè)HttpContext,將路徑為/myserver請求映射到MyHttpHandler處理器 httpServer.createContext('/myserver', new MyHttpHandler()); //設(shè)置服務(wù)器的線程池對象 httpServer.setExecutor(Executors.newFixedThreadPool(10)); //啟動服務(wù)器 httpServer.start(); }}
HttpServer:HttpServer主要是通過帶參的create方法來創(chuàng)建,第一個(gè)參數(shù)InetSocketAddress表示綁定的ip地址和端口號。第二個(gè)參數(shù)為int類型,表示允許排隊(duì)的最大TCP連接數(shù),如果該值小于或等于零,則使用系統(tǒng)默認(rèn)值。
createContext:可以調(diào)用多次,表示將指定的url路徑綁定到指定的HttpHandler處理器對象上,服務(wù)器接收到的所有路徑請求都將通過調(diào)用給定的處理程序?qū)ο髞硖幚怼?/p>
setExecutor:設(shè)置服務(wù)器的線程池對象,不設(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路徑請求的處理器類 */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(); }}
運(yùn)行HttpServerStarter,在瀏覽器中訪問如下:
以上就是Java 如何實(shí)現(xiàn)一個(gè)http服務(wù)器的詳細(xì)內(nèi)容,更多關(guān)于Java 實(shí)現(xiàn)http服務(wù)器的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. ASP.NET泛型三之使用協(xié)變和逆變實(shí)現(xiàn)類型轉(zhuǎn)換2. 如何在jsp界面中插入圖片3. jsp實(shí)現(xiàn)登錄界面4. PHP循環(huán)與分支知識點(diǎn)梳理5. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)6. XML基本概念XPath、XSLT與XQuery函數(shù)介紹7. jsp+servlet簡單實(shí)現(xiàn)上傳文件功能(保存目錄改進(jìn))8. JSP數(shù)據(jù)交互實(shí)現(xiàn)過程解析9. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)10. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案
