Skip to content
Advertisement

How to extract the relative url from the absolute url in Java

I have this website:

https://asd.com/somestuff/another.html

and I want to extract the relative part out of it:

somestuff/another.html

How do I do that?

EDIT: I was offered an answer to a question, but the problem there was to build the absolute url out of the relative which is not what I’m interested in.

Advertisement

Answer

You could use the getPath() method of the URL object:

URL url = new URL("https://asd.com/somestuff/another.html");
System.out.println(url.getPath());  // prints "/somestuff/another.html"

Now, this only brings the actual path. If you need more information (the anchor or the parameters passed as get values), you need to call other accessors of the URL object:

URL url = new URL("https://asd.com/somestuff/another.html?param=value#anchor");
System.out.println(url.getPath());  // prints "/somestuff/another.html"
System.out.println(url.getQuery()); // prints "param=value"
System.out.println(url.getRef());   // prints "anchor"

A possible use to generate the relative URL without much code, based on Hiru’s answer:

URL absolute = new URL(url, "/");
String relative = url.toString().substring(absolute.toString().length());
System.out.println(relative); // prints "somestuff/another.html?param=value#anchor"
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement