How to redirect a request using JAX-RS?

I want to send a REST request to another server.

I am using JAX-RS with Jersey and Tomcat. I tried it with setting See Other response and adding Location header, but it is not real.

If I use:

 request.getRequestDispatcher(url).forward(request, response); 

I get:

  • java.lang.StackOverflowError : If the url is a relative path
  • java.lang.IllegalArgumentException : Path http://website.com does not start with the / character (I think the forward is only legal in the same servlet context).

How can I send a request?

+4
source share
1 answer

Forward

RequestDispatcher allows RequestDispatcher to redirect a request from a servlet to another resource on the same server , for more details see.

You can use the JAX-RS API and make your resource class as a proxy server to redirect the request to a remote server:

 @Path("/foo") public class FooResource { private Client client; @PostConstruct public void init() { this.client = ClientBuilder.newClient(); } @POST @Produces(MediaType.APPLICATION_JSON) public Response myMethod() { String entity = client.target("http://example.org") .path("foo").request() .post(Entity.json(null), String.class); return Response.ok(entity).build(); } @PreDestroy public void destroy() { this.client.close(); } } 

Redirection

If the redirection is right for you, you can use the Response API:

See an example:

 @Path("/foo") public class FooResource { @POST @Produces(MediaType.APPLICATION_JSON) public Response myMethod() { URI uri = // Create your URI return Response.temporaryRedirect(uri).build(); } } 

It might be worth mentioning that UriInfo can be UriInfo into your resource classes or methods to get useful information such as the base URI and the absolute request path .

 @Context UriInfo uriInfo; 
+4
source

Source: https://habr.com/ru/post/1491424/


All Articles