如何使用JAX-RS转发请求? [英] How to forward a request using JAX-RS?
问题描述
我想将REST请求转发给另一台服务器。
I want to forward a REST request to another server.
我将JAX-RS与Jersey和Tomcat一起使用。我尝试设置查看其他
响应并添加位置
标头,但这不是真正的前进。
I use JAX-RS with Jersey and Tomcat. I tried it with setting the See Other
response and adding a Location
header, but it's not real forward.
如果我使用:
request.getRequestDispatcher(url).forward(request, response);
我得到:
-
java.lang.StackOverflowError
:如果网址是相对路径 -
java.lang .IllegalArgumentException
:路径 http://website.com 不以<$ c $开头c> / 字符(我认为转发只在同一个servlet上下文中合法)。
java.lang.StackOverflowError
: If the url is a relative pathjava.lang.IllegalArgumentException
: Path http://website.com does not start with a/
character (I think the forward is only legal in the same servlet context).
如何我可以转发请求吗?
How can I forward a request?
推荐答案
转发
RequestDispatcher
允许您将请求从servlet转发到同一服务器上的另一个资源 。有关详细信息,请参阅此答案。
Forward
The RequestDispatcher
allows you to forward a request from a servlet to another resource on the same server. See this answer for more details.
您可以使用 JAX-RS Client API 并使您的资源类作为代理将请求转发到远程服务器:
You can use the JAX-RS Client API and make your resource class play as a proxy to forward a 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();
}
}
重定向
如果重定向适合您,您可以使用 回复
API:
Redirect
If a redirect suits you, you can use the Response
API:
-
Response.seeOther(URI)
:用于重定向后POST(又名POST /重定向/ GET)模式。 - < a href =https://javaee.github.io/javaee-spec/javadocs/javax/ws/rs/core/Response.html#temporaryRedirect-java.net.URI- =nofollow noreferrer>
Response.temporaryRedirect(URI)
:用于临时重定向。
Response.seeOther(URI)
: Used in the redirect-after-POST (aka POST/redirect/GET) pattern.Response.temporaryRedirect(URI)
: Used for temporary redirection.
参见示例:
@Path("/foo")
public class FooResource {
@POST
@Produces(MediaType.APPLICATION_JSON)
public Response myMethod() {
URI uri = // Create your URI
return Response.temporaryRedirect(uri).build();
}
}
可能值得一提的是 <$可以在您的资源类或方法中注入c $ c> UriInfo 以获取一些有用的信息,例如基本URI 和请求的绝对路径。
@Context
UriInfo uriInfo;
这篇关于如何使用JAX-RS转发请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!