21

I'm using Jersey to create REST API. I have one POST method and as a response from that method, the user should be redirected to a custom URL like http://example.com that doesn't have to be related to API.

I was looking at other similar questions on this topic here but didn't find anything that I could use.

2 Answers 2

40

I'd suggest altering the signature of the JAX-RS-annotated method to return a javax.ws.rs.core.Response object. Depending on whether you intend the redirection to be permanent or temporary (i.e. whether the client should update its internal references to reflect the new address or not), the method should build and return a Response corresponding to an HTTP-301 (permanent redirect) or HTTP-302 (temporary redirect) status code.

Here's a description in the Jersey documentation regarding how to return custom HTTP responses: https://jersey.java.net/documentation/latest/representations.html#d0e5151. I haven't tested the following snippet, but I'd imagine that the code would look something like this, for HTTP-301:

@POST
public Response yourAPIMethod() {
    URI targetURIForRedirection = ...;
    return Response.seeOther(targetURIForRedirection).build();
}

...or this, for HTTP-302:

@POST
public Response yourAPIMethod() {
    URI targetURIForRedirection = ...;
    return Response.temporaryRedirect(targetURIForRedirection).build();
}
2
  • Worked. Thanks. It saved my day Aug 16, 2014 at 10:46
  • 3
    I just tried these out and it seems that as of 2.23 Jersey returns a 303 for seeOther and a 307 for temporaryRedirect (which make a lot more sense than, respectively, 301 Moved Permanently and 302 Found). Caching on 301s would really screw things up for the OP's use case.
    – elhefe
    Sep 10, 2016 at 0:06
0

This worked for Me

 @GET
  @Path("/external-redirect2")
  @Consumes(MediaType.APPLICATION_JSON)
  public Response method2() throws URISyntaxException {

    URI externalUri = new URI("https://in.yahoo.com/?p=us");
    return Response.seeOther(externalUri).build();
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.