[英]How to get the path of a URL
你想要这样的东西:
String path = new URL("http://www.costo.com/test1/test2").getPath();
实际上,这将给你/test1/test2
。 你只需删除第一个/
获得你想要的东西:
path = path.replaceFirst("/", "");
现在你将在path
有test1/test2
。
我对使用Java URL类进行性能疑问只是从URL中提取路径并认为这是一种过度杀伤力。
因此,我写了三个方法,它们都使用不同的方法从给定的URL中提取路径。
对于给定的URL,所有三种方法都被调用1000000次。
结果是:
#1 (getPathviaURL) took: 860ms
#2 (getPathViaRegex) took: 3763ms
#3 (getPathViaSplit) took: 1365ms
代码 - 随意优化它:
public static void main(String[] args) {
String host = "http://stackoverflow.com/questions/5564998/how-to-get-the-path-of-a-url";
long start1 = System.currentTimeMillis();
int i = 0;
while (i < 1000000) {
getPathviaURL(host);
i++;
}
long end1 = System.currentTimeMillis();
System.out.println("#1 (getPathviaURL) took: " + (end1 - start1) + "ms");
Pattern p = Pattern.compile("(?:([^:\\/?#]+):)?(?:\\/\\/([^\\/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?");
long start2 = System.currentTimeMillis();
int i2 = 0;
while (i2 < 1000000) {
getPathViaRegex(host, p);
i2++;
}
long end2 = System.currentTimeMillis();
System.out.println("#2 (getPathViaRegex) Took: " + (end2 - start2) + "ms");
long start3 = System.currentTimeMillis();
int i3 = 0;
while (i3 < 1000000) {
getPathViaSplit(host);
i3++;
}
long end3 = System.currentTimeMillis();
System.out.println("#3 (getPathViaSplit) took: " + (end3 - start3) + "ms");
}
public static String getPathviaURL(String url) {
String path = null;
try {
path = new URL(url).getPath();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return path;
}
public static String getPathViaRegex(String url, Pattern p) {
Matcher m = p.matcher(url);
if (m.find()) {
return m.group(3);
}
return null;
}
public static String getPathViaSplit(String url) {
String[] parts = url.split("/");
parts = Arrays.copyOfRange(parts, 3, parts.length);
String joined = "/" + StringUtils.join(parts, "/");
return joined;
}
使用URL
类的URL.getPath()
方法。
你可以这样做:
URL url = new URL("http://www.costo.com/test1/test2");
System.out.println(url.getPath());
如果你想从你的应用程序的URL获取它,如http:// localhost:8080 / test1 / test2 / main.jsp 。 使用可以使用
request.getRequestURI() //result will be like test1/test2
我建议使用URI
class,因为它也可以处理相对路径。 这是使用 URI 和 URL 实现相同功能的示例代码:
String urlStr = "http://localhost:8080/collections-in-java?error=true";
try {
URI uri = URI.create(urlStr);
System.out.println(uri.getPath());
URL url1 = new URL(urlStr);
System.out.println(url1.getPath());
} catch (MalformedURLException e) {
e.printStackTrace();
}
上面的代码将产生相同的结果。 如果路径可能是相对的,则 URI 很有用,例如/some/path/collections-in-java?error=true
对于这种情况, URI.getPath()
将返回/some/path/collections-in-java
但URL.getPath()
将抛出MalformedURLException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.