Giriş
Şu satırı dahil ederiz
import com.sun.net.httpserver.HttpServer;
Açıklaması şöyle
JEP 408 is an enhancement proposal introducing a new feature in #Java 18: a simple HTTP server that is easy to use and requires no external dependencies. This server is designed to be lightweight, easy to configure, and capable of serving static content and dynamic content generated by a Java program.The new Java Simple Web Server is based on the existing HttpServer class, but it simplifies creating and configuring an HTTP server. It provides a default configuration that is suitable for many use cases, but it also allows for customization through a simple #API.
constructor
Şöyle yaparız
Örnek
HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 80), 0);
createContext metodu - pathÖrnek
Şöyle yaparız. setHandler() metodunu çağırmak gerekir.
Örnekler yukarıda
start metodu
server.createContext("/");
server.start();
createContext metodu - path + Handler
Örnek
Şöyle yaparız
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3000), 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newCachedThreadPool());
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "Hello world!";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
setExecutor metodu
Örnek
Şöyle yaparız. Burada Executors.newCachedThreadPool() ile sınırsız sayıda thread kullanılıyor
server.setExecutor(Executors.newCachedThreadPool());
Örnek
Şöyle yaparız. Burada Executors.newVirtualThreadPerTaskExecutor() ile Project Loom'a ait Virtual Threads kullanılıyor.
public static void main(String[] args) throws Exception {
HttpServer server = HttpServer.create(new InetSocketAddress(3000), 0);
server.createContext("/", new MyHandler());
server.setExecutor(Executors.newVirtualThreadPerTaskExecutor());
server.start();
}
static class MyHandler implements HttpHandler {
@Override
public void handle(HttpExchange t) throws IOException {
String response = "Hello world!";
t.sendResponseHeaders(200, response.length());
OutputStream os = t.getResponseBody();
os.write(response.getBytes());
os.close();
}
}
setHandler metodu
start metodu
Hiç yorum yok:
Yorum Gönder