Java URI.resolve

Cpa picture Cpa · Mar 28, 2010 · Viewed 19.9k times · Source

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?

Answer

Mike Tunnicliffe picture Mike Tunnicliffe · Mar 29, 2010

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"