假设您可以确定要使用的上下文,vanilla URL 类可能会帮助您完成大部分工作。这里有些例子:
package grimbo.url;
import java.net.MalformedURLException;
import java.net.URL;
public class TestURL {
public static void main(String[] args) {
// context1
URL c1 = u(null, "http://www.example.com/page.html");
u(c1, "http://www.example.com/page.html");
u(c1, "/page.html");
u(c1, "page.html");
u(c1, "../page.html");
u(c1, "#paragraphA");
System.out.println();
// context2
URL c2 = u(null, "http://www.example.com/path/to/page.html");
u(c2, "http://www.example.com/page.html");
u(c2, "/page.html");
u(c2, "page.html");
u(c2, "../page.html");
u(c2, "#paragraphA");
}
public static URL u(URL context, String url) {
try {
URL u = null != context ? new URL(context, url) : new URL(url);
System.out.println(u);
return u;
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
}
}
结果是:
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/../page.html
http://www.example.com/page.html#paragraphA
http://www.example.com/path/to/page.html
http://www.example.com/page.html
http://www.example.com/page.html
http://www.example.com/path/to/page.html
http://www.example.com/path/page.html
http://www.example.com/path/to/page.html#paragraphA
如您所见,有些结果不是您想要的。因此,也许您尝试new URL(value)
先使用解析 URL,如果结果是 a,MalformedURLException
您可以尝试相对于上下文 URL。