Java URL : Get root of URL object (remove path)

标签 java

有没有办法从给定的 URL 中仅获取方案 + 主机 + 端口。

所以我的意思是,我想删除路径 url 段。

URL aURL = new URL("http://example.com:80/docs/books/tutorial"
                       + "/index.html?name=networking#DOWNLOADING");

我一直在玩这个:

System.out.println("protocol = " + aURL.getProtocol());
System.out.println("authority = " + aURL.getAuthority());
System.out.println("host = " + aURL.getHost());
System.out.println("port = " + aURL.getPort());
System.out.println("path = " + aURL.getPath());
System.out.println("query = " + aURL.getQuery());
System.out.println("filename = " + aURL.getFile());
System.out.println("ref = " + aURL.getRef());

输出是:

protocol = http
authority = example.com:80
host = example.com
port = 80
path = /docs/books/tutorial/index.html
query = name=networking
filename = /docs/books/tutorial/index.html?name=networking
ref = DOWNLOADING

我想要得到的是 http://example.com:8080

的新 URL 对象

有什么想法吗?

最佳答案

我发现更短的方法可以维护除路径部分之外的所有内容,请使用URI.resolve()

URL url = new URL("http://example.com:8081/api/test");
System.out.println(url)// prints "http://example.com:8081/api/test"

URL urlNoPath = url.resolve("/");
System.out.println(url)// prints "http://example.com:8081/"

关于Java URL : Get root of URL object (remove path),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56988955/

相关文章:

使用 commons-digester 进行解析时出现 java.lang.NumberFormatException

java - Gson 输出 com.google.gson.JsonSyntaxException : java. io.EOFException:第 1 行第 501 列输入结束

java - 如何仅通过这种回溯找到第一个解决方案

java - 如何同步访问多个线程访问的数组列表?

java - JDBC - 结果集数据处理 : Strange behaviour : default fetchsize returned

java - getResourceStream 写入文件

java - 更改照片的KeyEvent不起作用,如何激活它?

java - Eclipse paho Mqtt :Getting java. io.EOF 异常

java - Android Studio : Discrepency between Gradle versions mentioned in Gradle file and File > Project Structure > Project

java - 如何在 Eclipse 中更改 Android 的 Java 构建路径?