我有一个设置,托管我的REST服务器的tomcat服务器将调用从HTTP(端口9080)重定向到HTTPS(端口9443)。
我正在使用jersey 2.5实现,无法管理客户端以遵循重定向。
我发现了这个问题(Jersey client doesn't follow redirects),不过它是为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);
哪个失败,因为客户端似乎没有遵循重定向。以下是日志记录筛选器提供的内容:
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
从泽西文档我明白,所有需要做的就是将ClientProperties.FOLLOW_REDIRECTS属性添加到客户端,但显然情况并非如此。我还发现消息表明可能是客户端过滤器需要遵循重定向,但没有找到关于此的示例或指南。
因此,如果任何有jax.rs和重定向经验的人可以指向某些方向/文档/示例代码,我真的很感激。
答案 0 :(得分:11)
正确的方法是:
webTarget.property(ClientProperties.FOLLOW_REDIRECTS, Boolean.TRUE);
答案 1 :(得分:7)
好吧,我终于想到了这个使用过滤器,不确定这是最好的解决方案,任何评论都表示赞赏:
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());
}
}
答案 2 :(得分:1)
这是因为如果URL方案在重定向期间发生更改,则Http(s)UrlConnection不会遵循重定向。所以可能的解决方案是use alternative client transport connector。
这看起来像
SSLContextProvider ssl = new TrustAllSSLContextImpl(); // just trust all certs
JerseyClientBuilder clientBuilder = new JerseyClientBuilder()
.sslContext(ssl.getContext())
.register(LoggingFilter.class);
clientBuilder.getConfiguration().connectorProvider(new org.glassfish.jersey.apache.connector.ApacheConnectorProvider());
JerseyClient client = clientBuilder.build();
Response response = client
.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);