我正在尝试使用 Jersey 和 Glassfish Grizzly 在 Java 中编写 REST 服务。我有一个非常简单的内部工作案例,但似乎无法从外部地址调用服务器。我尝试使用各种不同的具有外部可见 IP 的机器对,并尝试在服务器中指定实际 IP 地址而不是 localhost
,但没有任何作用。我有点松散地遵循官方用户指南 here .我的资源:
package resources;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
@Path("/simpleREST")
public class SimpleRESTResource
{
@GET
@Produces("text/plain")
public String getMessage()
{
return "Message from server\n";
}
}
和服务器:import java.io.IOException;
import java.net.URI;
import javax.ws.rs.core.UriBuilder;
import org.glassfish.grizzly.http.server.HttpServer;
import com.sun.jersey.api.container.grizzly2.GrizzlyServerFactory;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.api.core.ResourceConfig;
public class Main
{
public static final URI BASE_URI = UriBuilder.fromUri("http://localhost").port(9998).build();
public static void main(String[] args) throws IOException
{
System.out.println("Starting grizzly...");
ResourceConfig rc = new PackagesResourceConfig("resources");
HttpServer myServer = GrizzlyServerFactory.createHttpServer(BASE_URI, rc);
System.out.println(String.format("Jersey app started with WADL available at %s/application.wadl\n" +
"Try out %s/simpleREST\nHit enter to stop it...", BASE_URI, BASE_URI));
System.in.read();
myServer.stop();
}
}
在同一台机器上,我可以使用curl -X GET localhost:9998/simpleREST
或者curl -X GET [external numeric address]:9998/simpleREST
非常感谢您提供任何建议。解决方案
我通过将服务器 URI 设置为
http://0.0.0.0:9998
解决了这个问题。而不是 localhost
, 127.0.0.1
,或实际地址。
最佳答案
要使服务器 IP 地址在 localhost 之外可见,您必须首先打开必要的防火墙端口(如果有),或使用“0.0.0.0”而不是“localhost”,以便服务器监听所有 IP 地址和网络适配器。在您的本地网络中进行测试之前,请尝试从您的客户端设备 ping 您的服务器设备以检查是否存在实际连接或设备是否根本没有连接。
关于rest - Jersey Grizzly REST 服务在本地主机之外不可见,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12077670/