泽西jax.rs客户端2.5遵循重定向

dev*_*arn 12 rest redirect tomcat jersey-client jersey-2.0

我有一个设置,托管我的REST服务器的tomcat服务器将调用从HTTP(端口9080)重定向到HTTPS(端口9443).

我正在使用jersey 2.5实现,无法管理客户端以遵循重定向.

我发现了这个问题(泽西岛客户端不遵循重定向),但它是为泽西1.X系列提供的,而且API已经改变了.

我尝试使用以下测试代码将其调整为2.5:

 SSLContextProvider ssl = new TrustAllSSLContextImpl(); // just trust all certs
 Response response  =     ClientBuilder.newBuilder()
     .sslContext(ssl.getContext()).newClient()
     .register(LoggingFilter.class)
     .target("http://testhost.domain.org:9080/rest.webapp/api/v1/hello/")
     .property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE)
     .request().get();   
 Assertions.assertThat(response.getStatus()).isNotEqualTo(302);
Run Code Online (Sandbox Code Playgroud)

由于客户端似乎没有遵循重定向,因此失败了.以下是日志记录筛选器提供的内容:

Feb 14, 2014 12:23:45 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Sending client request on thread main
1 > GET http://testhost.domain.org:9080/rest.webapp/api/v1/hello/

Feb 14, 2014 12:23:45 PM org.glassfish.jersey.filter.LoggingFilter log
INFO: 1 * Client response received on thread main
1 < 302
1 < Cache-Control: private
1 < Content-Length: 0
1 < Date: Fri, 14 Feb 2014 11:38:59 GMT
1 < Expires: Thu, 01 Jan 1970 01:00:00 CET
1 < Location: https://testhost.domain.org:9443/rest.webapp/api/v1/hello/
1 < Server: Apache-Coyote/1.1
Run Code Online (Sandbox Code Playgroud)

从泽西文档中我了解到,所有需要做的就是将ClientProperties.FOLLOW_REDIRECTS属性添加到客户端,但显然情况并非如此.我还发现消息表明可能需要客户端过滤器按照重定向,但没有找到关于此的示例或指南.

因此,如果任何有jax.rs和重定向经验的人可以指向我某些方向/ docs /示例代码,我真的很感激.

小智 12

正确的方法是:

webTarget.property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
Run Code Online (Sandbox Code Playgroud)

  • 你确定最后一个参数是"假"吗?在我看来,这只是禁用重定向:) (5认同)
  • 这应该是`webTarget.property(ClientProperties.FOLLOW_REDIRECTS,Boolean.TRUE)`,正如先前的评论者所指出的那样. (4认同)
  • -1,因为这只是 jersey,但原作者明确要求 JAX-RS(这是他当前正在使用的 jersey 实现的标准)。 (2认同)

dev*_*arn 9

好吧,我终于想出了使用过滤器,不确定这是最好的解决方案,任何意见表示赞赏:

public class FollowRedirectFilter implements ClientResponseFilter
{
   @Override
   public void filter(ClientRequestContext requestContext, ClientResponseContext responseContext) throws IOException
   {
      if (responseContext.getStatusInfo().getFamily() != Response.Status.Family.REDIRECTION)
         return;

      Response resp = requestContext.getClient().target(responseContext.getLocation()).request().method(requestContext.getMethod());

      responseContext.setEntityStream((InputStream) resp.getEntity());
      responseContext.setStatusInfo(resp.getStatusInfo());
      responseContext.setStatus(resp.getStatus());
   }
}
Run Code Online (Sandbox Code Playgroud)