Best approach to redirect an URL using REST
There are several types of redirects
According to the RFC 7231, the current reference for the semantics and content of the HTTP/1.1, there are several types of redirects. They are all
Redirects that indicate the resource might be available at a different URI, as provided by the Location field, as in the status codes
301
(Moved Permanently),302
(Found), and307
(Temporary Redirect).Redirection that offers a choice of matching resources, each capable of representing the original request target, as in the
300
(Multiple Choices) status code.Redirection to a different resource, identified by the Location field, that can represent an indirect response to the request, as in the
303
(See Other) status code.Redirection to a previously cached result, as in the
304
(Not Modified) status code.
The correct one depend on your needs. However, these are the most commons:
The
301
(Moved Permanently) status code indicates that the target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs. [...]
The
303
(See Other) status code indicates that the server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, which is intended to provide an indirect response to the original request. [...]
The
307
(Temporary Redirect) status code indicates that the target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI. [...]
Performing the redirects in JAX-RS
By the code you posted in the question, I believe you are using the JAX-RS API. If so, you can perform the redirects as following:
URI uri = ...
return Response.status(Status.MOVED_PERMANENTLY).location(uri).build();
- 303 See Other (aka POST/redirect/GET):
URI uri = ...
return Response.seeOther(uri).build();
URI uri = ...
return Response.temporaryRedirect(uri).build();
For more details, the Response
class documentation may be useful.
Other details that can be useful when using JAX-RS
You also can inject the UriInfo
in your REST endpoints:
@Context
UriInfo uriInfo;
And get some useful information, such as the base URI and the absolute path of the request. It will be useful when building the URI for redirection.
A resource method with redirection will be like:
@Path("/foo")
public class MyEndpoint {
@Context
private UriInfo uriInfo;
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod() {
URI uri = uriInfo.getBaseUriBuilder().path("bar").build();
return Response.temporaryRedirect(uri).build();
}
}
user1770589
Updated on December 24, 2020Comments
-
user1770589 over 3 years
Can anyone suggest me which is the best approach to redirect an URL using REST among the below two ways:
1. httpResponse.sendRedirect("URL"); 2. Response.temporaryRedirect(new URI("path"));