Jsoup - Проверить URL перенаправления

Jsoup - Проверить URL перенаправления

В этой статье мы покажем вам, как использовать Jsoup для проверки, будет ли URL перенаправлять.

1. Перенаправление URL

Обычно URL-адрес перенаправления возвращает код HTTP 301 или 307, а целевой URL-адрес будет существовать в поле заголовка ответа «location».

Просмотрите образец заголовка ответа HTTP

HTTP код: 301 перемещен навсегда

{
    Location=http://example.com
    Server=GSE,
    Cache-Control=no-cache,
    no-store,
    max-age=0,
    must-revalidate
}

2. Пример Jsoup

2.1 By default, Jsoup will follow the redirect recursively and display the final URL.

RedirectExample.java

package com.example.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 : http://www.example.com/mongodb/mongodb-remove-a-field-from-array-documents/

2.2 To test the URL redirection, set followRedirects to 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 This example will print out the redirect URLs recursively.

RedirectExample.java

package com.example.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 : http://www.example.com/mongodb/mongodb-remove-a-field-from-array-documents/