在检索重定向URL之前使用Apache HttpHead进行URI编码

时间:2014-10-17 08:43:53

标签: java apache-httpclient-4.x url-redirection apache-httpcomponents http-head

我必须获取一些简短网址的重定向网址,以检查我是否可以下载最终页面。 HttpHead用于获取最终目标网址(请参阅下面的代码)。

HttpClient client = HttpClientBuilder.create().build();

HttpHead httpHead = new HttpHead("http://bit.ly/1DfSWSs");

HttpClientContext context = HttpClientContext.create();
client.execute(httpHead, context);
List<URI> redirectLocations = context.getRedirectLocations();
if (redirectLocations != null && !redirectLocations.isEmpty()) {
    for (URI redirectURI : redirectLocations) {
        //TODO print all
    }
}

问题在于代码中的URL示例。重定向url中包含空格,因此无法创建URI。

有没有办法在调用getRedirectLocations方法之前编码URI对象?

1 个答案:

答案 0 :(得分:1)

自定义重定向策略是您的朋友

CloseableHttpClient client = HttpClientBuilder.create()
        .setRedirectStrategy(new DefaultRedirectStrategy() {
            @Override
            protected URI createLocationURI(final String location) throws ProtocolException {
                // One can try to rewrite malformed redirect locations 
                //at this point
                return super.createLocationURI(location);
            }
        })
        .build();