Jordi
Jordi

Reputation: 23247

Java URL: Get root of URL object (remove path)

Is there any way to get only the scheme + host + port from a given URL.

So I mean, I want to remove path url segment.

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                       + "/index.html?name=networking#DOWNLOADING");

I've been playing with this:

System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());

Output is:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

what I want to get is a new URL object to http://example.com:8080

Any ideas?

Upvotes: 8

Views: 4808

Answers (2)

kdubb
kdubb

Reputation: 483

I found shorter method that maintains everything but the path portion, use URI.resolve().

// For java.net.URI
URI uri = URI.create("http://example.com:8081/api/test");
System.out.println(uri) // prints "http://example.com:8081/api/test"

URI uriNoPath = uri.resolve("/");
System.out.println(uriNoPath) // prints "http://example.com:8081/"


// For java.net.URL, convert to URI first and then back to URL
URL url = new URL("http://example.com:8081/api/test");
URL urlNoPath = url.toURI().resolve("/").toURL();
System.out.println(urlNoPath); // prints "http://example.com:8081/"

Upvotes: 5

user11044402
user11044402

Reputation:

Just use the URL constructor to build a new URL.

URL newUrl = new URL(aURL.getProtocol(), aURL.getHost(), 8080, "/");

Upvotes: 3

Related Questions