JDK轻量级HttpServer

使用的JDK版本:jdk1.7.0_80

API地址:

https://docs.oracle.com/javase/7/docs/jre/api/net/httpserver/spec/com/sun/net/httpserver/HttpExchange.html

public class HttpServerDemo {
	public static void main(String[] args) throws IOException {
		InetSocketAddress addr = new InetSocketAddress(5555);
		HttpServer server = HttpServer.create(addr, 0);
		server.createContext("/server", new MyHttpHandler());
		server.setExecutor(Executors.newCachedThreadPool());
		server.start();
		System.out.println("Server is listening on port 5555");
	}
}

class MyHttpHandler implements HttpHandler {

	@Override
	public void handle(HttpExchange exchange) throws IOException {
		Headers responseHeaders = exchange.getResponseHeaders();
		responseHeaders.set("Content-Type", "text/plain");
		exchange.sendResponseHeaders(200, 0);
		OutputStream responseBody = exchange.getResponseBody();
		responseBody.write("helloworld".getBytes());
		responseBody.flush();
		responseBody.close();
	}

}
访问地址: http://localhost:5555/server


你可能感兴趣的:(java)