import java.net.URL; import java.util.HashMap; import java.util.Map; import java.util.Collections; /** * A crappy little toy exercise not intended for actual usage. * Given a URL as first argument, prints the component parts on separate lines * all fancy-like. Also does some silly guessing when there's no port * provided. Unmazing. */ public class URLParts { public static final Map defaultPorts; static { Map tmpMap = new HashMap(); tmpMap.put("http", 80); tmpMap.put("https", 443); tmpMap.put("file", -1); defaultPorts = Collections.unmodifiableMap(tmpMap); } public static void main(String[] args) throws Exception { for (int i = 0; i < args.length; i++) { showParts(new URL(args[i])); } } public static void showParts(URL url) { String protocol = url.getProtocol(); int port = url.getPort(); if (port == -1) { port = getDefaultPortForProtocol(protocol); } showPart("protocol", protocol); showPart("host", url.getHost()); showPart("port", Integer.toString(port)); } public static void showPart(String name, String value) { System.out.println(String.format("%s: %s", name, value)); } public static int getDefaultPortForProtocol(String protocol) { if (protocol == null) { protocol = "http"; } else { protocol = protocol.toLowerCase(); } return defaultPorts.get(protocol); } }