从Java中的相对URL构建绝对URL

Mar*_*itt 16 java url relative-url

我无法从相对URL构建绝对URL而无需使用String hackery ...

特定

http://localhost:8080/myWebApp/someServlet
Run Code Online (Sandbox Code Playgroud)

方法内部:

   public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
Run Code Online (Sandbox Code Playgroud)

什么是最"正确"的建设方式:

http://localhost:8080/myWebApp/someImage.jpg
Run Code Online (Sandbox Code Playgroud)

(注意,必须是绝对的,而不是相对的)

目前,我是通过构建字符串来实现的,但必须有更好的方法.

我查看了新URI/URL的各种组合,我最终得到了

http://localhost:8080/someImage.jpg
Run Code Online (Sandbox Code Playgroud)

非常感谢

Ham*_*aya 39

使用java.net.URL

 URL baseUrl = new URL("http://www.google.com/someFolder/");
 URL url = new URL(baseUrl, "../test.html");
Run Code Online (Sandbox Code Playgroud)