The latest version is JAX-RS 2.0 [JSR 339], which was released as part of the Java EE 7 platform.
JAX-RS stands for JAVA API for RESTful Web Services. JAX-RS is a JAVA based programming language API and specification to provide support for created RESTful Web Services. Its 2.0 version was released on the 24th May 2013.
You can inject HttpServletRequest
:
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getIp(@Context HttpServletRequest req) {
String remoteHost = req.getRemoteHost();
String remoteAddr = req.getRemoteAddr();
int remotePort = req.getRemotePort();
String msg = remoteHost + " (" + remoteAddr + ":" + remotePort + ")";
return Response.ok(msg).build();
}
As Luke said, when using Heroku, the remote host is the AWS application tier, therefore the EC2 ip address.
"X-Forwarded-For" header is the answer:
String ip = "0.0.0.0";
try {
ip = req.getHeader("X-Forwarded-For").split(",")[0];
} catch (Exception ignored){}
Based on @user647772 and @Ethan fusion. Thanks to them ;)
inject HttpServletRequest:
@GET
@Produces(MediaType.TEXT_PLAIN)
public Response getFromp(@Context HttpServletRequest req) {
String from = _getUserFrom(req);
return Response.ok(from).build();
}
private String _getUserFrom(HttpServletRequest req) {
String xForwardedFor = req.getHeader("X-Forwarded-For");
xForwardedFor = xForwardedFor != null && xForwardedFor.contains(",") ? xForwardedFor.split(",")[0]:xForwardedFor;
String remoteHost = req.getRemoteHost();
String remoteAddr = req.getRemoteAddr();
int remotePort = req.getRemotePort();
StringBuffer sb = new StringBuffer();
if (remoteHost != null
&& !"".equals(remoteHost)
&& !remoteHost.equals(remoteAddr)) {
sb.append(remoteHost).append(" ");
}
if (xForwardedFor != null
&& !"".equals(xForwardedFor)) {
sb.append(xForwardedFor).append("(fwd)=>");
}
if (remoteAddr != null || !"".equals(remoteAddr)) {
sb.append(remoteAddr).append(":").append(remotePort);
}
return sb.toString();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With