在工作中经常会遇到简单实用 HTTP server 的场景,可是又不需要 Spring MVC 或者 web容器那样重的东西。这种情况下 JavaSE 就可以满足我们的要求了。
上代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 package web;import com.sun.net.httpserver.Headers;import com.sun.net.httpserver.HttpExchange;import com.sun.net.httpserver.HttpHandler;import com.sun.net.httpserver.HttpServer;import org.springframework.stereotype.Service;import javax.annotation.PostConstruct;import java.io.IOException;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.net.HttpURLConnection;import java.net.InetSocketAddress;@Service public class SimpleServer { @PostConstruct public void initHttpServer () throws IOException { HttpServer server = HttpServer.create(new InetSocketAddress (8418 ), 0 ); server.createContext("/test" , new MyHandler ()); server.setExecutor(null ); server.start(); } static class MyHandler implements HttpHandler { @Override public void handle (HttpExchange httpExchange) throws IOException { System.out.println("receive" ); String requestMethod = httpExchange.getRequestMethod(); if (requestMethod.equalsIgnoreCase("GET" )) { Headers responseHeaders = httpExchange.getResponseHeaders(); responseHeaders.set("Content-Type" , "text/html;charset=utf-8" ); String queryParams = httpExchange.getRequestURI().getQuery(); System.out.println(queryParams); String response = "this is server" ; httpExchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.getBytes("UTF-8" ).length); try (OutputStream responseBody = httpExchange.getResponseBody(); OutputStreamWriter writer = new OutputStreamWriter (responseBody, "UTF-8" )) { writer.write(response); } } } } }
参考
CSDN
stackoverflow