这段代码可以在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 中丢失了。