Java |用于从URL获取协议://domain.port的API

时间:2015-08-20 09:11:49

标签: java

我有网址作为推荐人,并希望从中获取协议和域名。

例如:如果网址为https://test.domain.com/a/b/c.html?test=hello,则输出必须为https://test.domain.com。我已经完成了http://docs.oracle.com/javase/7/docs/api/java/net/URI.html,我似乎无法找到任何可以直接执行此操作的方法。

我不使用Spring,因此无法使用Sprint类(如果有的话)。

伙计我可以编写自定义登录来从URL获取端口,域和协议,但是寻找已经实现此功能的API,并且可以最大限度地减少我测试各种场景的时间。

3 个答案:

答案 0 :(得分:4)

使用您的String值创建一个新的URL对象,并在其上调用getHost()或任何其他方法,如下所示:

URL url = new URL("https://test.domain.com/a/b/c.html?test=hello");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();

// if the port is not explicitly specified in the input, it will be -1.
if (port == -1) {
    return String.format("%s://%s", protocol, host);
} else {
    return String.format("%s://%s:%d", protocol, host, port);
}

答案 1 :(得分:3)

要详细说明@mthmulders答案中的@Rupesh,

getAuthority()给出域和端口。因此,您只需将getProtocol()作为前缀进行连接:

URL url = new URL("https://test.domain.com/a/b/c.html?test=hello");
String protocol = url.getProtocol();
String authority = url.getAuthority();
return String.format("%s://%s", protocol, authority);

答案 2 :(得分:0)

getAuthority()返回主机和端口,但是getHost()仅返回主机名。因此,如果URL为“ https://www.hello.world.com:80/x/y/z.html?test=hello”,则getAuthority()返回www.hello.world.com:80,而getHost()返回www.hello.world.com

示例

URL url = new URL("https://www.hello.world.com:80/x/y/z.html?test=hello");
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
String authority = url.getAuthority();

System.out.println("Host "+host);   // www.hello.world.com
System.out.println("authority "+authority);   // www.hello.world.com:80

//Determining Protocol plus host plus port (if any) url using Authority (simple single line step)
System.out.println("ProtocolHostPortURL:: "+ String.format("%s://%s", protocol, authority));

//Determining Protocol plus host plus port (if any) url using Authority (multi line step)
//If the port is not explicitly specified in the input, it will be -1.
if (port == -1) {
    System.out.println("ProtocolHostURL1:: "+ String.format("%s://%s", protocol, host));        
} else {
    System.out.println("ProtocolHostPortURL2:: "+ String.format("%s://%s:%d", protocol, host, port));    
}