Java URL Connection getRealURL(URL url)

Here you can find the source of getRealURL(URL url)

Description

Follow redirections for given url.

License

Open Source License

Parameter

Parameter Description
url url.

Exception

Parameter Description
IOException error with IO.
InterruptedException task cancelled.

Return

last redirected url.

Declaration

public static URL getRealURL(URL url) throws IOException, InterruptedException 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;

import java.util.List;
import java.util.Map;

public class Main {
    /**//from   w  ww .  j  a  v a  2s .co  m
     * Follow redirections for given url.
     * 
     * @param url
     *            url.
     * @return last redirected url.
     * @throws IOException
     *             error with IO.
     * @throws InterruptedException
     *             task cancelled.
     */
    public static URL getRealURL(URL url) throws IOException, InterruptedException {
        URLConnection connection = url.openConnection();
        Map<String, List<String>> header = connection.getHeaderFields();
        while (isRedirected(header)) {
            // Check for interrupt.
            if (Thread.currentThread().isInterrupted()) {
                throw new InterruptedException();
            }
            // Get redirection.
            url = new URL(header.get("Location").get(0));
            connection = url.openConnection();
            header = connection.getHeaderFields();
        }
        return url;
    }

    /**
     * Check if the header contains a redirection.
     * 
     * @param header
     *            header.
     * @return if it contains a redirection.
     */
    public static boolean isRedirected(final Map<String, List<String>> header) {
        for (final String hv : header.get(null)) {
            if (hv.contains(" 301 ") || hv.contains(" 302 ")) {
                return true;
            }
        }
        return false;
    }
}

Related

  1. getLines(final URL url, final int linesToRead)
  2. getOutputStream(final URL outputURL)
  3. getOutputStream(URL url)
  4. getPage(String url)
  5. getPageContent(String inputUrlString)
  6. getRemoteTimestamp(final String url)
  7. getRequest(URLConnection conn)
  8. getRequestHeaders(URLConnection conn)
  9. getResultsWithEncoding(URLConnection source, String encoding)