package org.jorgecardoso.net; /** * Utility class for HTTP redirects. * * Contains static methods that build the absolute URL * based on the original URL (the one that originated the * redirect response) and on the location * header. * * * @author Jorge Cardoso * @version 1.00, 16/07/2005 */ public class HTTPRedirect { /** * Returns the URL of the redirected webpage. * * baseURL is the requested HTTP URL and * location is the HTTP Location Header value. * * @param baseURL The requested HTTP URL. * @param location The Location Header value. * * @return An absolute URL that corresponds to the target URL. */ public static String redirectURL(String baseURL, String location) { if (location.startsWith("http://")) { return location; } else if (location.startsWith("/")) { return "http://" + getHost(baseURL) + "location"; } else { if (baseURL.endsWith("/")) { return baseURL + location; } else { return baseURL + "/" + location; } } } /** * Returns the host part of the URL, without the trailing slash. * http://jorgecardoso.org/ - returns jorgecardoso.org * @param URL The URL to get the host part from. Must start with http:// * * @return The host part of the URL. */ public static String getHost(String URL) { if (!URL.startsWith("http://")) { throw new java.lang.IllegalArgumentException("URL must start with 'http://'"); } String n = URL.substring(7); // strip http:// int slashPos = n.indexOf('/'); if ( slashPos == -1) { // no slash, so this is the host only return n; } else { return n.substring(0, slashPos+1); } } /** * Indicates whether this URL has a file part. * * @param URL The URL to check for the file part. * * @return true if this URL has a file part, false otherwise. */ public static boolean hasFile(String URL) { URL = URL.trim(); if (!URL.startsWith("http://")) { throw new java.lang.IllegalArgumentException("URL must start with 'http://'"); } String n = URL.substring(7); // strip http:// int lastSlashPos = n.lastIndexOf('/'); if (lastSlashPos == -1) { //no slash, so no file return false; } else if (lastSlashPos < n.length()) { return true; } return false; } }