Skip to content

Instantly share code, notes, and snippets.

@paxan
Last active December 17, 2015 09:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paxan/5588336 to your computer and use it in GitHub Desktop.
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/)
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)));
}
}
}
@paxan
Copy link
Author

paxan commented May 15, 2013

For instance:

$ java -cp ... RedirectSpy http://t.co/GKwKPqQ9KX http://t.co/D6VT308Yzz
http://blog.22tracks.com/on-to-the-next-chapter/ ← http://wv.ly/18LRVmO ← http://t.co/GKwKPqQ9KX
http://instagram.com/p/ZVz0x8vfMU/ ← http://t.co/D6VT308Yzz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment