这段代码适用于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
。