I need to get the full url with the host name or IP address from a restful request made to my rest service. Is there any way this can be done?
Similar to InetAddress ip = ip.getHostName(); in java.
I need to get the full url with the host name or IP address from a restful request made to my rest service. Is there any way this can be done?
Similar to InetAddress ip = ip.getHostName(); in java.
When you say InetAddress ip = ip.getHostName(); you will get the hostname of the machine where your rest service is running, to get the the name of the machine from where request is originated you will need to use something similar to request.getRemoteHost(); this value could be depend on the network environment of the machine from where request was originated.
to get full url please refer below post. What's the best way to get the current URL in Spring MVC?
With Jersey you can do the following
String clientHost = req.getRemoteHost(); // req is HttpServletRequest
String clientAddr = req.getRemoteAddr();
@GET
@Path("/test")
public Response test(@Context HttpContext context) {
String url = context.getRequest().getAbsolutePath().getPath();
String query = context.getRequest().getRequestUri().toASCIIString();
String reqString = url + " + " + query;
return Response.status(Status.OK).entity(reqString).build();
}
– Ashir Khan
Mar 10 '15 at 07:18
If you use UriInfo
, it will get you the server-side URI
, not the client-side one.
If you want the client-side URI
, you will have to use HttpServletRequest
:
@POST
@Path("/test")
public Response uriTest(@Context HttpServletRequest request) {
try {
URI baseUri = new URL(request.getRequestURL().toString()).toURI();
System.out.println(baseUri.getHost());
System.out.println(baseUri.getPort());
return Response.ok(null).build();
} catch (MalformedURLException | URISyntaxException e) {
throw new IllegalStateException("Error building the base URI.", e);
}
}
Using CDI and @Context, similar to the comment by Ashir Khan above, the requestContext or parts of the request context can be made available at run time. Many types can be bound by the @Context annotation and injected by the container, although it would be better to:
Sounds like a lot, but is as simple as (a modification on) Ashir's code:
@GET
@Path("/test")
// Look Ma, no hands!
public Response test(@Context javax.ws.rs.core.UriInfo uriInfo) {
return Response.status(Status.OK).entity(uriInfo.getBaseUri()).build();
}
You can use the UriInfo
class and bind it using the @Context
annotation, then at every request you can access the URI information like Hostname, Port, Request Path etc.
Here is an example -
@POST
@Path("/test")
public Response uriTest(@Context UriInfo uriInfo){ //helps you get all URI related information.
System.out.println(uriInfo.getBaseUri().getHost());
System.out.println(uriInfo.getBaseUri().getPort());
return Response.ok(null).build();
}
You can read more about URIInfo
here