如何从 java 中的 HttpHeaders 对象中查找客户端 ip 地址?

How to find the client ip address from a HttpHeaders object in java?

如何从 java 中的 HttpHeaders 对象中查找客户端 ip 地址?

请在下面找到我的服务器端代码:

@Path("/login")
public class Login
{
    DBConnection dBConnection = new DBConnection();

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String checkLogin(@QueryParam("username")String username,@QueryParam("password")String password,@QueryParam("clientid")String clientno,@QueryParam("callback")String callback,@Context HttpHeaders headers)
    {

        JSONObject loginresult = new JSONObject();
        try
        {
            String query = QuerySelector.getQuery("user.checklogin");
            loginresult = dBConnection.queryForJSONObject(query, username,password,clientno);
           //here i need to get the client ip address from my headers object.        

        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
        return callback + "(" + loginresult.toString() + ")" ;
    }
}

你可以试试这个:

request.getHeader("Remote_Addr");

如果 returns 为 null 则尝试:

request.getRemoteAddr();

您可以通过 @Context HttpServletRequest request 获取它,就像:

String ip = request.getRemoteAddr();

新方法签名:

@GET
@Produces(MediaType.APPLICATION_JSON)
public String checkLogin(@QueryParam("username")String username,@QueryParam("password")String password,@QueryParam("clientid")String clientno,@QueryParam("callback")String callback,@Context HttpServletRequest request)