我有这个网站:
https://asd.com/somestuff/another.html
我想从中提取相关部分:
somestuff/another.html
我怎么做?
编辑:我得到了一个问题的答案,但问题是建立了相对的绝对网址,这不是我感兴趣的.
解决方法@H_404_14@
您可以使用URL对象的
getPath()
方法:
URL url = new URL("https://asd.com/somestuff/another.html");
System.out.println(url.getPath()); // prints "/somestuff/another.html"
现在,这只会带来实际的路径.如果您需要更多信息(锚点或作为获取值传递的参数),您需要调用URL对象的其他访问者:
URL url = new URL("https://asd.com/somestuff/another.html?param=value#anchor");
System.out.println(url.getPath()); // prints "/somestuff/another.html"
System.out.println(url.getQuery()); // prints "param=value"
System.out.println(url.getRef()); // prints "anchor"
根据Hiru’s answer,可能会使用生成相对URL而没有太多代码:
URL absolute = new URL(url,"/");
String relative = url.toString().substring(absolute.toString().length());
System.out.println(relative); // prints "somestuff/another.html?param=value#anchor"
getPath()
方法:
URL url = new URL("https://asd.com/somestuff/another.html"); System.out.println(url.getPath()); // prints "/somestuff/another.html"
现在,这只会带来实际的路径.如果您需要更多信息(锚点或作为获取值传递的参数),您需要调用URL对象的其他访问者:
URL url = new URL("https://asd.com/somestuff/another.html?param=value#anchor"); System.out.println(url.getPath()); // prints "/somestuff/another.html" System.out.println(url.getQuery()); // prints "param=value" System.out.println(url.getRef()); // prints "anchor"
根据Hiru’s answer,可能会使用生成相对URL而没有太多代码:
URL absolute = new URL(url,"/"); String relative = url.toString().substring(absolute.toString().length()); System.out.println(relative); // prints "somestuff/another.html?param=value#anchor"