Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "merge" two URIs in Java?

Tags:

java

This is an absolute URI of the server:

URI base = new URI("http://localhost/root?a=1");

This is a relative URI:

URI rel = new URI("/child?b=5");

Now I'm trying to apply relative one to the absolute and receive:

URI combined = base + rel; // somehow
assert combined.equals(new URI("http://localhost/root/child?a=1&b=5"));

Is it possible to do such a manipulation with JDK or some library?

like image 769
yegor256 Avatar asked Nov 25 '11 18:11

yegor256


2 Answers

URL mergedURL = new URL(new URL(baseUrl), relativeUrl); 

To pass on base url's parameters to merged url, you'll have to extract them manually by calling URL#getQuery and append them to new URL

Something like,

String finalUrl = mergedUrl.toString() + "&" + baseUrl.getQuery(); 

It will take an if() to decide whether an '&' is required to join them depending on what mergedUrl looks like.

like image 195
d-live Avatar answered Sep 22 '22 21:09

d-live


URI (and File also) have a constructor which accepts an existing URI (or File).
It is MADE for relative URI's:
URL mergedURL = new URL(baseUrl, relativeUrl);
To merge two File paths you can use:
File mergedFile = new File(directoryFile, fileOrDir);
If you use mergedFile.getName() you get the filename if it isn't a directory.
This is not possible for an URL.

like image 40
BronzeByte Avatar answered Sep 19 '22 21:09

BronzeByte