Java HTML / XML How to - Connect to a web page with jsoup








Question

We would like to know how to connect to a web page with jsoup.

Answer

import java.io.IOException;
import java.net.HttpURLConnection;
//w ww.j ava  2 s  .c  om
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;

public class Main {

  public static void main(String[] args) throws IOException {
    String redirectUrl = getRedrectUrl("http://java2s.com");
    redirectUrl = getRedrectUrl(redirectUrl); 
    System.out.println(redirectUrl);
  }

  private static String getRedrectUrl(String url) throws IOException {
    Response response = Jsoup.connect(url).followRedirects(false).execute();
    int status = response.statusCode();
    if (status == HttpURLConnection.HTTP_MOVED_TEMP
        || status == HttpURLConnection.HTTP_MOVED_PERM
        || status == HttpURLConnection.HTTP_SEE_OTHER) {
      return response.header("location");
    }
    return null;
  }
}