I have to get redirection URLs for some short url to check if I can download final page. HttpHead is used to get final destination url (see code below).
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
}
}
Problem is with URL example in code. Redirection url contains space in it, so URI cannot be created.
It there any way to encode URI object before being able to call getRedirectLocations method?
Custom redirect strategy is your friend
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();