一、相关类
1.HttpServer
表示一个服务器实例,需要绑定一个IP地址和端口号
2.HttpContext
服务器监听器的上下文
3.HttpHandler
上下文对应的http请求处理器
4.HttpExchange
监听器回调时传入的参数,封装了http请求和响应的所有数据操作
二、使用
public class MyServer {
public static void main(String[] args) throws IOException {
HttpServer httpServer = HttpServer.create(new InetSocketAddress(9090), 0);
httpServer.createContext("/hello", new MyHandler());
httpServer.start();
System.out.println("server start...");
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange exchange) throws IOException {
String response = "Hello World";
exchange.sendResponseHeaders(200, 0);
OutputStream os = exchange.getResponseBody();
os.write(response.getBytes("UTF-8"));
os.close();
}
}
}
来源:CSDN
作者:Luck_ZZ
链接:https://blog.csdn.net/Luck_ZZ/article/details/104119903