Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dineshbhagat/16209576ee648758f0a48c3c0bd45bd0 to your computer and use it in GitHub Desktop.
Save dineshbhagat/16209576ee648758f0a48c3c0bd45bd0 to your computer and use it in GitHub Desktop.
MyServer.java
import com.sun.net.httpserver.Filter;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpHandlers;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.Request;
import com.sun.net.httpserver.SimpleFileServer;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Predicate;

/**
 * <a href="https://www.baeldung.com/simple-web-server-java-18">simple-web-server-java-18</a>
 * If you need socket level implementation <a href="https://dev.to/mateuszjarzyna/build-your-own-http-server-in-java-in-less-than-one-hour-only-get-method-2k02">Using socket</a>
 */
public class MyServer {

    static class MyItemHandler implements HttpHandler {

        /**
         * Handle the http://localhost:8080/item?name=tv
         * request and generate an appropriate response.
         * See {@link HttpExchange} for a description of the steps
         * involved in handling an exchange.
         *
         * @param exchange the exchange containing the request from the
         *                 client and used to send the response
         */
        @Override
        public void handle(HttpExchange exchange) throws IOException {
            final String requestMethod = exchange.getRequestMethod();
            final String requestUri = exchange.getRequestURI().toString();

            Map<String, String> queryMap = getQueryMap(requestUri);
            String requestParamValue = queryMap.entrySet().iterator().next().getValue();

            if (requestMethod.equals("GET")) {
                final OutputStream responseBody = exchange.getResponseBody();
                // you can send encoded html message as well
                final String userMessage = "Hello World";
                StringBuilder htmlBuilder = new StringBuilder();

                htmlBuilder
                        .append("<html>")
                        .append("<body>")
                        .append("<h1>")
                        .append("Hello ")
                        .append(requestParamValue)
                        .append("</h1>")
                        .append("</body>")
                        .append("</html>");
                byte[] userMessageBytes;
                if (requestParamValue != null && !requestParamValue.isBlank()) {
                    userMessageBytes = htmlBuilder.toString().getBytes(StandardCharsets.UTF_8);
                } else {
                    userMessageBytes = userMessage.getBytes(StandardCharsets.UTF_8);
                }
                //following code is must and order is important, i.e. set status code first before writing body
                exchange.sendResponseHeaders(200, userMessageBytes.length);
                responseBody.write(userMessageBytes);
                responseBody.flush();
                responseBody.close();
            }
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {

        // Prepare thread pool
        final ExecutorService executorService = Executors.newFixedThreadPool(10);
        final int port = 8080;

        // Filters
        Filter filter = SimpleFileServer.createOutputFilter(System.out, SimpleFileServer.OutputLevel.INFO);

        // Global handlers
        HttpHandler allowedResponse = HttpHandlers.of(200, Headers.of("Allow", "GET"), "Welcome");
        HttpHandler deniedResponse = HttpHandlers.of(401, Headers.of("Deny", "GET"), "Denied");
        Predicate<Request> findAllowedPath = r -> r.getRequestURI()
                .getPath().equals("/test/allowed");
        HttpHandler handler = HttpHandlers.handleOrElse(findAllowedPath, allowedResponse, deniedResponse);

        final HttpServer server = HttpServer.create(new InetSocketAddress(port), 0, "/", handler, filter);
        server.setExecutor(executorService);

        // Custom Handlers
        server.createContext("/item", new MyItemHandler());

        server.start();
        System.out.println(" Server started on port " + port);
    }

    @NotNull
    private static Map<String, String> getQueryMap(String requestUri) {
        if (requestUri == null || requestUri.isBlank()) {
            return Collections.emptyMap();
        }
        Map<String, String> queryMap = new HashMap<>();
        final String[] requestParams = requestUri.split("\\?");
        if (requestParams.length > 0) {
            final String[] queryParam = requestParams[1].split("&");
            for (String s : queryParam) {
                final String[] requestValue = s.split("=");
                if (requestValue.length > 0) {
                    queryMap.put(requestValue[0], requestValue[1]);
                }
            }
        }
        return queryMap;
    }
}
MyClient.java
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * <a href="https://www.baeldung.com/java-httpclient-post">java-httpclient-usage</a>
 * <a href="https://www.vogella.com/tutorials/JavaHttpClient/article.html">httpclient-fluent-api</a>
 */
public class MyClient {
    public static void main(String[] args) {
        try (var httpClient = HttpClient.newHttpClient()) {
            // use the client
            final String url = "http://localhost:8080/item?item1=tv&item2=cd&item3=mouse";
            syncApiCall(url, httpClient);
            asyncApiCall(url, httpClient);
        }
    }

    private static void asyncApiCall(String url, HttpClient httpClient) {
        final HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(url)).GET().header("User-Agent", "Mozilla/5.0").build();
        try {
            final CompletableFuture<HttpResponse<String>> httpResponse = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofString());

            System.out.println(httpResponse.get().statusCode() + ":" + httpResponse.get().body());
        } catch (InterruptedException | ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    private static void syncApiCall(String url, HttpClient httpClient) {
        final HttpRequest httpRequest = HttpRequest.newBuilder(URI.create(url)).GET().header("User-Agent", "Mozilla/5.0").build();
        try {
            final HttpResponse<String> httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
            System.out.println(httpResponse.statusCode() + ":" + httpResponse.body());
        } catch (IOException | InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment