Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 278
Kaloyan Roussev Avatar asked Jun 15 '15 11:06

Kaloyan Roussev


People also ask

What is absolute URL relative URL?

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.

What is relative URL in Java?

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.

Is absolute URL better than relative?

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.


2 Answers

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"
like image 199
Chop Avatar answered Sep 28 '22 04:09

Chop


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/
like image 43
Nagarz Avatar answered Sep 28 '22 06:09

Nagarz