如何获取URL的路径

有一个URL,如何检索其路径部分?

http://www.costo.com/test1/test2

如何获得“test1 / test2”

你想要这样的东西:

String path = new URL("http://www.costo.com/test1/test2").getPath(); 

实际上,这将给你/test1/test2 。 你只需删除第一个/获得你想要的东西:

 path = path.replaceFirst("/", ""); 

现在你将在pathtest1/test2

我有使用Java URL类的性能疑问,只是从URL中提取路径,并认为这是一种矫枉过正。

因此,我编写了三种方法,它们都使用不同的方法从给定的URL中提取路径。

  1. 第一种方法使用Java URL类中的URL.getPath方法。
  2. 第二种方法使用我在SO中找到的正则表达式 (我丢失了源链接,否则我会在这里给作者提供信用)。
  3. 第三种方法使用数组拆分和连接来获得相同的结果。

对于给定的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 = new URL("http://www.google.com/in/on"); System.out.println(url.getPath()); 

另见

  • 的Javadoc

使用URL类的URL.getPath()方法。

你可以这样做:

  URL url = new URL("http://www.costo.com/test1/test2"); System.out.println(url.getPath());