从Java中的相对URL构建一个绝对URL
-
21-09-2019 - |
题
我无法建立从一个相对URL的绝对URL不诉诸字符串两轮牛车...
鉴于
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
我们已经失去了我们的BaseURL /first
。
不隶属于 StackOverflow