假设您可以计算出使用哪种上下文,那么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。