Last active
December 17, 2015 09:38
-
-
Save paxan/5588336 to your computer and use it in GitHub Desktop.
A demo of shortened URL expansion using Apache HttpComponents (http://hc.apache.org/)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.base.Joiner; | |
import org.apache.http.HttpRequest; | |
import org.apache.http.HttpResponse; | |
import org.apache.http.ProtocolException; | |
import org.apache.http.client.methods.HttpHead; | |
import org.apache.http.client.methods.HttpUriRequest; | |
import org.apache.http.impl.client.DefaultHttpClient; | |
import org.apache.http.impl.client.DefaultRedirectStrategy; | |
import org.apache.http.protocol.HttpContext; | |
import java.io.IOException; | |
import java.net.URI; | |
import java.util.Deque; | |
import java.util.LinkedList; | |
public class RedirectSpy { | |
public static class SpyStrategy extends DefaultRedirectStrategy { | |
public final Deque<URI> history = new LinkedList<>(); | |
public SpyStrategy(URI uri) { | |
history.push(uri); | |
} | |
@Override | |
public HttpUriRequest getRedirect( | |
HttpRequest request, | |
HttpResponse response, | |
HttpContext context) throws ProtocolException { | |
HttpUriRequest redirect = super.getRedirect(request, response, context); | |
history.push(redirect.getURI()); | |
return redirect; | |
} | |
} | |
public static Deque<URI> expand(String uri) { | |
try { | |
HttpHead head = new HttpHead(uri); | |
SpyStrategy spy = new SpyStrategy(head.getURI()); | |
DefaultHttpClient client = new DefaultHttpClient(); | |
client.setRedirectStrategy(spy); | |
// FIXME: the following completely ignores HTTP errors: | |
client.execute(head); | |
return spy.history; | |
} | |
catch (IOException e) { | |
throw new RuntimeException(e); | |
} | |
} | |
public static void main(String[] args) throws IOException { | |
Joiner link = Joiner.on(" \u2190 "); | |
for (String uri: args) { | |
System.out.println(link.join(expand(uri))); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For instance: