goofing around with URLs in java

cat-town
Dan Buch 13 years ago
parent b70a59831a
commit f4f658a7f7

@ -1,5 +1,8 @@
CFLAGS += -g -Wall -Wextra CFLAGS += -g -Wall -Wextra
all: temperatures %.class:%.java
javac -d $(PWD) $^
all: temperatures URLParts.class
.PHONY: all .PHONY: all

@ -0,0 +1,52 @@
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<String, Integer> defaultPorts;
static {
Map<String, Integer> tmpMap = new HashMap<String, Integer>();
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);
}
}
Loading…
Cancel
Save