From 2ba2a07d6435fbde00497cff143dd5d76143e78e Mon Sep 17 00:00:00 2001 From: adb Date: Thu, 14 Jan 2021 20:26:50 +0100 Subject: [PATCH] add httpServer --- src/sh/adb/RandomRedditMemesAPI/Main.java | 29 +++++++++++++++++++++-- 1 file changed, 27 insertions(+), 2 deletions(-) diff --git a/src/sh/adb/RandomRedditMemesAPI/Main.java b/src/sh/adb/RandomRedditMemesAPI/Main.java index 949742d..92aa534 100644 --- a/src/sh/adb/RandomRedditMemesAPI/Main.java +++ b/src/sh/adb/RandomRedditMemesAPI/Main.java @@ -1,8 +1,33 @@ package sh.adb.RandomRedditMemesAPI; +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.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; + public class Main { - public static void main(String[] args) { - // write your code here + public static void main(String[] args) throws IOException { + HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0); + server.createContext("/api/v1/", new MyHandler()); + server.setExecutor(null); + server.start(); + } + +} +class MyHandler implements HttpHandler { + @Override + public void handle(HttpExchange t) throws IOException { + InputStream is = t.getRequestBody(); + //is.read(); + String response = "This is the response"; + t.sendResponseHeaders(200, response.length()); + OutputStream os = t.getResponseBody(); + os.write(response.getBytes()); + os.close(); } }