Open In App

How to Set Up a Basic HTTP Server in Java?

In Java, setting up a basic HTTP server involves creating an application that listens for incoming HTTP requests and responses. In this article, we will discuss how to set up a basic HTTP server in Java.

Implementation Steps to Set Up a Basic HTTP Server

Program to Set up a Basic HTTP Server in Java

Below is the Program to Set up a Basic HTTP Server in Java:






// Java Program to Set up a Basic HTTP 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;
 
// Driver Class
public class SimpleHttpServer
{
    // Main Method
    public static void main(String[] args) throws IOException
    {
        // Create an HttpServer instance
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
 
        // Create a context for a specific path and set the handler
        server.createContext("/", new MyHandler());
 
        // Start the server
        server.setExecutor(null); // Use the default executor
        server.start();
 
        System.out.println("Server is running on port 8000");
    }
 
    // define a custom HttpHandler
    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange exchange) throws IOException
        {
            // handle the request
            String response = "Hello, this is a simple HTTP server response!";
            exchange.sendResponseHeaders(200, response.length());
            OutputStream os = exchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}

Output:

Below the terminal output is showing that the server is running on port number 8000.



Response:

Below we can see the response in browser.

Explanation of the Code:


Article Tags :