假設您可以計算出使用哪種上下文,那麼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,如果這導致MalformedURLException
,則可以嘗試相對於上下文URL。