Here is an example of a simple HTTP server in Java:

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("/", new MyHandler());
        server.setExecutor(null);
        server.start();
        System.out.println("Server started on port 8000");
    }

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

This code creates a simple HTTP server that listens on port 8000 and responds with "Hello, world!" for any request to the root URL. You can customize the response by changing the response variable in the MyHandler class.

Build code HTTP Server JAVA

原文地址: http://www.cveoy.top/t/topic/0zI 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录