tags:

views:

201

answers:

2
+2  Q: 

Java URI.resolve

I'm trying to resolve two URIs, but it's not as straightforward as I'd like it to be.

URI a = new URI("http://www.foo.com");
URI b = new URI("bar.html");

The trouble is that a.resolve(b).toString() is now "http://www.foo.combar.html". How can I get away with that?

A: 

Add a slash:

URI a = new URI("http://www.foo.com/");
Bozho
But I don't know beforehand if my url ends with a slash or not.Is the good practice to check it myself before resolving ? If so, I'd be quite disappointed. What's the point of resolving ?
Normally a URL for a main domain should be entered with a slash at the end. This has nothing to do with Java. If it's missing, it's probably corrected by the browser or when the request gets through to a DNS server. If the Java class doesn't compensate for this, it's up to you to control input.
James P.
+3  A: 

Sounds like you probably want to use URL rather than URI (which is more general and needs to deal with a less strict syntax.)

URI a = new URI("http://www.foo.com");
URI b = new URI("bar.html");
URI c = a.resolve(b);
c.toString()     -> "http://www.foo.combar.html"
c.getAuthority() -> "www.foo.com"
c.getPath()      -> "bar.html"

URI's toString() doesn't behave as you might expect, but given its general nature it may be that it should be forgiven.

Sadly URI's toURL() method doesn't behave quite as I would have hoped to give you what you want.

URL u = c.toURL();
u.toString()     -> "http://www.foo.combar.html"
u.getAuthority() -> "www.foo.combar.html"  --- Oh dear :(

So best just to start straight out with a URL to get what you want:

URL x = new URL("http://www.foo.com");
URL y = new URL(x, "bar.html");
y.toString() -> "http://www.foo.com/bar.html"
fd
+1 for emphasising the distinction between URI and URL
skaffman