consider the url is
http://www.google.com/a/b/myendpoint
All I want is the following
http://www.google.com/a/b/
One approach is to split the String url and join all the components except last one.
I am thinking if there could be a better way?
You can use lastIndexOf()
:
url.substring(0, url.lastIndexOf('/') + 1)
String url = "http://www.google.com/a/b/myendpoint";
System.out.println(url.substring(0, url.lastIndexOf('/') + 1));
http://www.google.com/a/b/
Use either of the following both are same
pathofURL = url.subString(0, url.lastIndexOf('/') + 1);
or if it has no Query
pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getPath();
pathofURL = pathofURL.subString(0, pathofURL.lastIndexOf('/') + 1);
It has Query alone
pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getPath();
It has Query and Reference
pathofURL = url.getProtocol() + "://" + url.getAuthority() + url.getFile();
Hope it helps, check the URL and use either of the above.
The simplest uses the URI.resolve method: url.toURI().resolve("").toURL()
. (You could start immediately with URIs.)
URL url = new URL("http://www.google/intl/eo/index.html");
URL url2 = url.toURI().resolve("favicon.ico").toURL(); // Or "" for the question.
System.out.println("url2: " + url2.toExternalForm());
// url2: http://www.google/intl/eo/favicon.ico
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.