How to extract relative url from absolute URL in Java

I have this site:

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

and I want to extract the relative part from it:

 somestuff/another.html 

How to do it?

EDIT: I was offered the answer to the question, but the problem was to create an absolute URL from a relative who is not interested.

+5
source share
5 answers

You can 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 leads only to the actual path. If you need additional information (anchor or 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" 

Possible use for generating relative URLs without a lot of 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" 
+7
source

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/ 
+2
source

The URL consists of the following elements (note that some optional elements are omitted): 1) scheme 2) host name 3) [port] 4) path 5) request 6) fragment Using the Java Java API, you can do the following:

 URL u = new URL("https://randomsite.org/another/randomPage.html"); System.out.println(u.getPath()); 

Edit # 1 If you see Chop's answer, if you have request elements in your url like

 ?name=foo&value=bar 

Using the getQuery() method does not return the path to the resource, but only part of the query.

+1
source

try it

Use it globally not only for .com

  URL u=new URL("https://asd.in/somestuff/another.html"); String u1=new URL(u, "/").toString(); String u2=u.toString(); String[] u3=u2.split(u1); System.out.println(u3[1]); //it prints: somestuff/another.html 
+1
source

You can do this using the snippet below.

  String str="https://asd.org/somestuff/another.html"; if(str.contains("//")) //To remove any protocol specific header. { str=str.split("//")[1]; } System.out.println(str.substring(str.indexOf("/")+1)); // taking the first '/' 
+1
source

All Articles