如何使用JAX-RS转发请求?

我想将REST请求转发给另一台服务器。

我使用JAX-RS与Jersey和Tomcat。 我尝试设置See Other响应并添加Location标头,但它不是真正的前进。

如果我使用:

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

我明白了:

  • java.lang.StackOverflowError :如果url是相对路径
  • java.lang.IllegalArgumentException :路径http://website.com不以/字符开头(我认为转发仅在同一个servlet上下文中合法)。

我该如何转发请求?

向前

RequestDispatcher允许您将请求从servlet转发到同一服务器上的另一个资源。 有关详细信息,请参阅此答案 。

您可以使用JAX-RS客户端API并使您的资源类作为代理来转发请求到远程服务器:

 @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(); } } 

重定向

如果重定向适合您,您可以使用Response API:

  • Response.seeOther(URI) :用于重定向后POST(又名POST /重定向/ GET)模式。
  • Response.temporaryRedirect(URI) :用于临时重定向。

看例子:

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

值得一提的是,可以在您的资源类或方法中注入UriInfo以获取一些有用的信息,例如基URI和请求的绝对路径 。

 @Context UriInfo uriInfo;