[英]Getting redirected URL in Apache HttpComponents
我正在使用Apache HttpComponents來獲取一些已爬網URL的網頁。 這些URL中有許多實際上實際上重定向到了不同的URL(例如,因為它們已經使用URL縮短器進行了處理)。 除了下載內容之外,我還要解析最終URL(即提供下載內容的URL),甚至更好的是重定向鏈中的所有URL。
我一直在瀏覽API文檔,但不知道可以在哪里進行鈎子。 任何提示將不勝感激。
一種方法是通過設置相關參數來關閉自動重定向處理,並通過檢查3xx響應自行完成操作,然后從響應“ Location”標頭中手動提取重定向位置。
這是有關如何使用Apache HttpComponents進行演示的完整演示 。
您需要像這樣擴展DefaultRedirectStrategy
:
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;
}
}
expand
方法發送HEAD請求,該請求導致client
在spy.history
deque中收集URI,因為它會自動重定向:
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);
}
}
您可能希望將最大重定向數設置為合理的值(而不是默認值100),如下所示:
BasicHttpParams params = new BasicHttpParams();
params.setIntParameter(ClientPNames.MAX_REDIRECTS, 5);
DefaultHttpClient client = new DefaultHttpClient(params);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.