如何使用 HttpServer class 将端口 8000 暴露给远程访问?

How to expose port 8000 to remote access using HttpServer class?

我制作这个小 api 是为了在遗留系统上提供一些 json。我无法向其中添加 Spring 或任何库,我认为这是一种简单的方法。虽然它在本地使用 curl localhost:8000/jms/health 工作,但当我远程尝试时,连接被拒绝。 运行 netstat 给我回了这个:

[userName@machineIp ~]$ sudo netstat -nlpt | grep 8000
tcp        0      0 127.0.0.1:8000              0.0.0.0:*                   LISTEN      25638/java

这是 class:

package somePackage;

import com.sun.net.httpserver.HttpServer;

import org.slf4j.Logger;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.Executors;

public class HealthHttp {

    public static void init(Logger log) throws IOException {
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8000), 0);
        server.createContext("/jms/health", http -> {

            String body = "{\"hello\":\"world\"}"; // any valid json

            byte[] bytes = body.getBytes(StandardCharsets.UTF_8);

            http.getResponseHeaders().set("Content-Type", "application/json; charset=" + StandardCharsets.UTF_8);

            http.sendResponseHeaders(200, bytes.length);
            OutputStream output = http.getResponseBody();
            output.write(bytes);
            output.flush();
            output.close();
        });
        server.setExecutor(Executors.newFixedThreadPool(1));
        server.start();
        log.info("Http health server initialized");
    }
}

我该如何解决这个问题?

如问题评论中所建议,将 localhost 更改为 0.0.0.0 允许来自所有外部地址的连接和环回