Home > Java > javaTutorial > How Can I Easily Create a Basic HTTP Server in Java?

How Can I Easily Create a Basic HTTP Server in Java?

Mary-Kate Olsen
Release: 2024-12-17 22:33:10
Original
707 people have browsed it

How Can I Easily Create a Basic HTTP Server in Java?

Creating a Basic HTTP Server in Java Using Java SE API

Problem:

Developers often face the challenge of creating HTTP servers in Java without manually parsing requests and formatting responses. Existing solutions involve tedious and error-prone code, which is prone to bugs and insufficient error handling.

Answer: Built-in HTTP Server in Java

Since Java SE 6, Oracle JRE includes a built-in HTTP server, known as jdk.httpserver module in Java 9. This server simplifies the process of creating basic HTTP servers, eliminating the need for manual request parsing and response formatting.

Example:

Here's a simple example of using the built-in HTTP server:

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class SimpleHttpServer {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}
Copy after login

This server responds with the message "This is the response" when a request is made to "/test".

Note on com.sun.* Classes:

While using com.sun.* classes is generally discouraged for implementation of Java API specifications, the built-in HTTP server is an exception. It is an integral part of the JDK and does not pose portability issues like the sun.* package.

The above is the detailed content of How Can I Easily Create a Basic HTTP Server in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template