[英]Java: What is the easiest way to get entire URL except last part?
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. 一种方法是拆分String url并加入除最后一个组件之外的所有组件。
I am thinking if there could be a better way? 我在想是否有更好的方法?
You can use lastIndexOf()
: 你可以使用
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 它只有Query
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. 希望它有所帮助,检查URL并使用上述任一方法。
The simplest uses the URI.resolve method: url.toURI().resolve("").toURL()
. 最简单的方法是使用URI.resolve方法:
url.toURI().resolve("").toURL()
。 (You could start immediately with URIs.) (您可以立即使用URI启动。)
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.