从URL字符串中提取主机名/域名

Ana*_*and 4 java string url

我有一个像这样的网址http://hostname:port_no/control/login.jsp.

我将上面的url存储在一些String.Now中,我需要hostname从String中提取.

我在我的Java代码中这样做

String domain = url.substring(url.indexOf('/') + 2, url.lastIndexOf(':'));
Run Code Online (Sandbox Code Playgroud)

我想知道是否有更好的方法来做同样的事情.

Kar*_*elG 11

您可以使用java.net.URI-class从字符串中提取主机名.

下面是一个方法,您可以从中提取字符串中的主机名.

public String getHostName(String url) {
    URI uri = new URI(url);
    String hostname = uri.getHost();
    // to provide faultproof result, check if not null then return only hostname, without www.
    if (hostname != null) {
        return hostname.startsWith("www.") ? hostname.substring(4) : hostname;
    }
    return hostname;
}
Run Code Online (Sandbox Code Playgroud)

上面给出了主机名,如果您的主机名以" hostname.com/...或" 开头www.hostname.com/...,它将以"主机名"返回.

如果给定的url是无效的(未定义的主机名),则返回null.


nii*_*74u 6

java.net.URL aURL;
try {
    aURL = new java.net.URL("http://example.com:80/docs/");
    System.out.println("host = " + aURL.getHost()); //example.com
} catch (MalformedURLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)


Pet*_*Mmm 5

java.net.URL u = new URL("http://hostname:port_no/control/login.jsp");
System.err.println(u.getHost());
Run Code Online (Sandbox Code Playgroud)

  • 的System.out.println()? (3认同)
  • @MaciejCygan 我相信这是一个 _awesome_ [troll](http://codegolf.stackexchange.com/tags/code-trolling/info)。 (2认同)