繁体   English   中英

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

[英]Building an absolute URL from a relative URL in Java

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

特定

http://localhost:8080/myWebApp/someServlet

方法内部:

   public void handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

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

http://localhost:8080/myWebApp/someImage.jpg

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

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

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

http://localhost:8080/someImage.jpg

非常感谢

使用java.net.URL

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

怎么样:

String s = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/someImage.jpg";

看起来你已经找到了困难的部分,这是你正在运行的主机。 其余的很简单,

String url = host + request.getContextPath() + "/someImage.jpg";

应该给你你需要的东西。

这段代码工作将在linux上 ,它可以只组合路径 ,如果你想要更多,URI的构造函数可能会有所帮助。

URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth").toString());

如果您的路径包含需要转义的内容,请首先使用URLEncoder.encode将其转义。

URL baseUrl = new URL("http://example.com/first");
URL targetUrl = new URL(baseUrl, Paths.get(baseUrl.getPath(), URLEncoder.encode(relativePath, StandardCharsets.UTF_8), URLEncoder.encode(filename, StandardCharsets.UTF_8)).toString());

例:

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get(baseUrl.getPath(), "second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

产量

http://example.com/first/second/third/fourth/fifth

baseUrl.getPath()非常重要,不要忘记它。

一个错误的例子:

import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Main {
    public static void main(String[] args) {
        try {
            URL baseUrl = new URL("http://example.com/first");
            Path relativePath = Paths.get("second", "/third", "//fourth//", "fifth");
            URL targetUrl = new URL(baseUrl, relativePath.toString());
            System.out.println(targetUrl.toString());
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }
}

产量

http://example.com/second/third/fourth/fifth

我们已经失去了/first中的BaseURL。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM