JDK >= 6
package com.demo.desktop; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; /** * 根据Java提供的API实现Http服务器 */ public class MyHttpServer { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { // 创建HttpServer服务器 HttpServer httpServer = HttpServer.create(new InetSocketAddress(8080), 10); //将 / 请求交给MyHandler处理器处理 httpServer.createContext("/", new MyHandler()); httpServer.start(); } } class MyHandler implements HttpHandler { public void handle(HttpExchange httpExchange) throws IOException { String content = "hello"; //设置响应头属性及响应信息的长度 httpExchange.sendResponseHeaders(200, content.length()); //获得输出流 OutputStream os = httpExchange.getResponseBody(); os.write(content.getBytes()); os.close(); } }
请求:
GET http://localhost:8080/
返回:
hello