Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.RandomAccessFile;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import java.nio.charset.StandardCharsets;
- import java.util.Random;
- public class Practicum {
- private static final int PORT = 8080;
- private static Random rnd = new Random();
- // IOException могут сгенерировать методы create() и bind(...)
- public static void main(String[] args) throws IOException {
- HttpServer httpServer = HttpServer.create();
- httpServer.bind(new InetSocketAddress(PORT), 0);
- httpServer.createContext("/hello", new HelloHandler());
- httpServer.createContext("/day", new MyHelloHandle());
- httpServer.start(); // запускаем сервер
- System.out.println("HTTP-сервер запущен на " + PORT + " порту!");
- httpServer.stop(1);
- }
- static class HelloHandler implements HttpHandler {
- @Override
- public void handle(HttpExchange httpExchange) throws IOException {
- System.out.println("Началась обработка /hello запроса от клиента.");
- String response = "Hey! Glad to see you on our server.";
- httpExchange.sendResponseHeaders(200, 0);
- try (OutputStream os = httpExchange.getResponseBody()) {
- os.write(response.getBytes());
- }
- }
- }
- static class MyHelloHandle implements HttpHandler {
- @Override
- public void handle(HttpExchange exchange) throws IOException {
- System.out.println("Началась обработка /day запроса от клиента.");
- String[] days = new String[]{"MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN"};
- int index = rnd.nextInt(7);
- String response = days[index];
- exchange.sendResponseHeaders(200, 0);
- try (OutputStream os = exchange.getResponseBody()) {
- os.write(response.getBytes());
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment