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.
An absolute URL contains all the information necessary to locate a resource. A relative URL locates a resource using an absolute URL as a starting point. In effect, the "complete URL" of the target is specified by concatenating the absolute and relative URLs.
Relative URLs are frequently used within HTML pages. For example, if the contents of the URL: http://java.sun.com/index.html contained within it the relative URL: FAQ.html it would be a shorthand for: http://java.sun.com/FAQ.html. The relative URL need not specify all the components of a URL.
An absolute URL contains more information than a relative URL does. Relative URLs are more convenient because they are shorter and often more portable. However, you can use them only to reference links on the same server as the page that contains them.
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"
if you know that the domain will always be .com then you can try something like this:
String url = "https://asd.com/somestuff/another.html";
String[] parts = url.split(".com/");
//parts[1] is the string after the .com/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With