Here you can find the source of getRealURL(URL url)
Parameter | Description |
---|---|
url | url. |
Parameter | Description |
---|---|
IOException | error with IO. |
InterruptedException | task cancelled. |
public static URL getRealURL(URL url) throws IOException, InterruptedException
//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; } }