Jsoup – リダイレクトURLを確認する
この記事では、Jsoupを使用してURLがリダイレクトされるかどうかを確認する方法を説明します。
1. URLリダイレクト
通常、リダイレクトURLは301または307のHTTPコードを返し、ターゲットURLは応答ヘッダー「
場所
」フィールドに存在します。
HTTP応答ヘッダーのサンプルを確認する
HTTPコード:301が永久に移動しました
{ Location=/ Server=GSE, Cache-Control=no-cache, no-store, max-age=0, must-revalidate }
2. Jsoupの例
2.1デフォルトでは、Jsoupはリダイレクトを再帰的に追跡し、最終的なURLを表示します。
RedirectExample.java
package com.mkyong.crawler; import java.io.IOException; import org.jsoup.Connection.Response; import org.jsoup.Jsoup; public class RedirectExample { public static void main(String[]args) throws IOException { String url = "http://goo.gl/fb/gyBkwR"; Response response = Jsoup.connect(url).execute(); System.out.println(response.statusCode() + " : " + response.url()); } }
出力
200 ://mongodb/mongodb-remove-a-field-from-array-documents/.... 2.2 URLリダイレクトをテストするには、 `followRedirects`をfalseに設定します。
Response response = Jsoup.connect(url).followRedirects(false).execute(); System.out.println(response.statusCode() + " : " + response.url());
//check if URL is redirect? System.out.println("Is URL going to redirect : " + response.hasHeader("location")); System.out.println("Target : " + response.header("location"));
出力
301 :
http://goo.gl/fb/gyBkwR
Is URL going to redirect : true
Target :
http://feeds.feedburner.com/
r/FeedForMkyong/
3/D__6Jqi4trqo/…
=== 3. Jsoupの例 3.1この例では、リダイレクトURLを再帰的に出力します。 RedirectExample.java
package com.mkyong.crawler;
import java.io.IOException;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
public class RedirectExample {
public static void main(String[]args) throws IOException {
String url = "http://goo.gl/fb/gyBkwR";
RedirectExample obj = new RedirectExample(); obj.crawl(url);
}
private void crawl(String url) throws IOException {
Response response = Jsoup.connect(url).followRedirects(false).execute();
System.out.println(response.statusCode() + " : " + url);
if (response.hasHeader("location")) { String redirectUrl = response.header("location"); crawl(redirectUrl); }
}
}
出力
301 :
http://goo.gl/fb/gyBkwR
301 :
http://feeds.feedburner.com/
r/FeedForMkyong/
3/D__6Jqi4trqo/…
200 ://mongodb/mongodb-remove-a-field-from-array-documents/….