我正在尝试访问正在调用我的休息服务器的客户端ip,但我只是将null作为响应。 Web服务器正在运行,我可以从Web浏览器访问。
我试过
@Context HttpServletRequest
还有
@Context ContainerRequest请求
request.getRequestHeader( “HTTP_FORWARDED”)
// HTTP_X_FORWARDED
// HTTP_CLIENT_IP
但两种情况都没有成功,响应为空或空白。
设置
Rest.java
PackageName.sublime-keymap
main.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
@Path("/rest")
public class Rest {
@GET
@Path("/test/")
@Produces(MediaType.APPLICATION_JSON)
public TestAddress test(@Context HttpServletRequest re){
System.out.println(re.getRemoteAddr());
TestAddress adr = new TestAddress();
adr.setAge(32);
adr.setName("Fidde");
adr.setSurename("Lass");
//System.out.println(uriInfo.getBaseUri());
return adr;
}
}
Pom.xml
http://maven.apache.org/xsd/maven-4.0.0.xsd">
4.0.0
测试
引导
罐
0.0.1-SNAPSHOT
import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory;
import org.glassfish.jersey.server.ResourceConfig;
import java.io.IOException;
import java.net.URI;
public class Main {
// Base URI the Grizzly HTTP server will listen on
public static final String BASE_URI = "http://localhost:8080/myapp/";
/**
* Starts Grizzly HTTP server exposing JAX-RS resources defined in this application.
* @return Grizzly HTTP server.
*/
public static HttpServer startServer() {
// create a resource config that scans for JAX-RS resources and providers
// in com.example package
final ResourceConfig rc = new ResourceConfig().packages("com.example");
// create and start a new instance of grizzly http server
// exposing the Jersey application at BASE_URI
return GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc);
}
/**
* Main method.
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
final HttpServer server = startServer();
System.out.println(String.format("Jersey app started with WADL available at "
+ "%sapplication.wadl\nHit enter to stop it...", BASE_URI));
System.in.read();
server.stop();
}
答案 0 :(得分:7)
HttpServletRequest
提供了一个应该返回远程IP地址的getRemoteAddr()
方法。
请注意,代理或NATing可能会修改IP地址。
编辑:
解决方案是注入一个灰熊请求:
@GET
@Path("/test/")
@Produces(MediaType.APPLICATION_JSON)
public TestAddress test(@Context org.glassfish.grizzly.http.server.Request re) {
System.out.println(re.getRemoteAddr());
...
}
这对我有用,但它完全依赖灰熊。