How to Create a Simple HTTP Server Using Java?

Question

What is the simplest method to create an HTTP server in Java, specifically for handling GET and POST requests without an application server?

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class SimpleHttpServer {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", new MyHandler());
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port 8080");
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange exchange) throws IOException {
            String response;
            if (exchange.getRequestMethod().equalsIgnoreCase("GET")) {
                response = "This is a response to GET request";
            } else if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
                response = "This is a response to POST request";
            } else {
                response = "Method not supported";
            }
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

Answer

Creating a simple HTTP server in Java can be straightforward, especially with the Built-in `HttpServer` class available in the `com.sun.net.httpserver` package. This implementation allows you to respond to both GET and POST requests without the need for a full-fledged application server.

import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

public class SimpleHttpServer {
    public static void main(String[] args) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress(8080), 0);
        server.createContext("/", new MyHandler());
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port 8080");
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange exchange) throws IOException {
            String response;
            if (exchange.getRequestMethod().equalsIgnoreCase("GET")) {
                response = "This is a response to GET request";
            } else if (exchange.getRequestMethod().equalsIgnoreCase("POST")) {
                response = "This is a response to POST request";
            } else {
                response = "Method not supported";
            }
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

Causes

  • You need a lightweight server solution in Java.
  • Your project requirements specify handling of GET and POST requests.
  • Avoiding the overhead of a large application server.

Solutions

  • Utilize the `HttpServer` class from the `com.sun.net.httpserver` package to create a basic HTTP server.
  • Implement a custom handler to manage incoming requests and provide responses accordingly.
  • Ensure your server listens on a specified port and can handle multiple request types.

Common Mistakes

Mistake: Not specifying the server port correctly.

Solution: Ensure the port number is open and accessible; in the code above, it's set to 8080.

Mistake: Ignoring request method handling, leading to unhandled requests.

Solution: Always check the request method (GET or POST) before responding.

Mistake: Forgetting to set response headers appropriately.

Solution: Use `exchange.sendResponseHeaders()` to set response codes and sizes.

Helpers

  • HTTP server in Java
  • Java simple server
  • GET POST Java server
  • Java HttpServer example
  • Creating HTTP server Java

Related Questions

⦿How to Differentiate Between Touch Press, Long Press, and Movement in Android?

Learn how to distinguish between touch press long press and movement events in Android including practical code examples and debugging tips.

⦿How to Retrieve a String Response Using Retrofit2 in Android?

Learn how to properly handle string responses with Retrofit2 in Android. Address common errors and implement effective solutions with code examples.

⦿How to Convert UTF-8 to ISO-8859-1 in Java While Preserving Character Representation

Learn how to convert UTF8 strings to ISO88591 in Java without losing character fidelity preserving singlebyte representation.

⦿How to Use a Collection as a Named Parameter in Hibernate HQL Queries?

Learn how to set a collection as a named parameter in Hibernate HQL queries with clear examples and common pitfalls.

⦿What is the Correct Order of Modifier Keywords in Java?

Learn the best practices for ordering modifier keywords in Java methods public private static and more.

⦿Why Does a Simple Java Application Consume 10GB of Virtual Memory on a 64-bit System Compared to 1GB on 32-bit?

Learn why a simple Java Hello World program uses significantly more virtual memory on a 64bit machine than on a 32bit system.

⦿Comparing Enum.values() and EnumSet.allOf(): Which Is Preferable?

Explore the differences between Enum.values and EnumSet.allOf including efficiency usability and best practices for using enums in Java.

⦿How to Check If a String Exists in an ArrayList in Java?

Learn how to check if a string is present in an ArrayList in Java and assign values based on the result.

⦿Is Objects.requireNonNull Method in Java Less Efficient Than Manual Null Checks?

Explore the efficiency of Javas Objects.requireNonNull vs. manual null checks. Review performance analysis and best practices for null validation.

⦿How to Convert UTC Date/Time String to a Readable Format in Java

Learn how to parse UTC datetime strings into more readable formats using Java with clear examples and explanations.

© Copyright 2025 - CodingTechRoom.com