Home >Java >javaTutorial >How Can I Create a Simple HTTP Server Using the Java SE API?

How Can I Create a Simple HTTP Server Using the Java SE API?

Linda Hamilton
Linda HamiltonOriginal
2024-12-12 10:28:12590browse

How Can I Create a Simple HTTP Server Using the Java SE API?

Using the Java SE API to Create an HTTP Server

Java SE includes HttpURLConnection for HTTP client functionality, but lacks an analogous server-side option. To avoid tedious manual parsing and formatting of HTTP requests and responses, consider the built-in HTTP server introduced in Java SE 6 located in the jdk.httpserver module.

Simple HTTP Server Example

Here's an example using the built-in HTTP server to handle requests:

package com.example;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

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.setExecutor(null); // Creates a default executor
        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.getBytes().length); // Specify charset for getBytes()
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Visit the specified URL (e.g., http://localhost:8000/test) with your browser to see the response:

This is the response

Using com.sun.* Classes

The com.sun. package is not forbidden for use as it pertains specifically to developer-written code that uses Sun/Oracle-specific APIs, not the built-in Java SE API. Thus, leveraging the com.sun. classes for the HTTP server is acceptable as these classes are included in all JDK implementations.

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

Statement:
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