Rest - how get IP address of caller

前端 未结 5 1360
离开以前
离开以前 2021-02-05 04:11

I am writing a Java Rest Web Service and need the caller\'s IP Address. I thought I saw this in the cookie once but now I don\'t see it. Is there a consistent place to get this

5条回答
  •  忘掉有多难
    2021-02-05 05:04

    Inject a HttpServletRequest into your Rest Service as such:

    import javax.servlet.http.HttpServletRequest;
    
    @GET
    @Path("/yourservice")
    @Produces("text/xml")
    public String activate(@Context HttpServletRequest requestContext,@Context SecurityContext context){
    
       String ipAddressRequestCameFrom = requestContext.getRemoteAddr();
    
       //Also if security is enabled
       Principal principal = context.getUserPrincipal();
       String userName = principal.getName();
    
    }
    

提交回复
热议问题