您好,登錄后才能下訂單哦!
利用Java 怎么模擬一個(gè)http服務(wù)器?相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。
在Java中可以使用HttpServer類來(lái)實(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主要是通過(guò)帶參的create方法來(lái)創(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)求都將通過(guò)調(diào)用給定的處理程序?qū)ο髞?lái)處理。
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)體長(zhǎng)度,必須在getResponseBody方法之前調(diào)用! httpExchange.sendResponseHeaders(200, responseContentByte.length); OutputStream out = httpExchange.getResponseBody(); out.write(responseContentByte); out.flush(); out.close(); } }
運(yùn)行HttpServerStarter,在瀏覽器中訪問(wèn)如下:
看完上述內(nèi)容,你們掌握利用Java 怎么模擬一個(gè)http服務(wù)器的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。