How to get parent URL in Java?

前端 未结 4 1259
眼角桃花
眼角桃花 2020-12-11 15:51

In Objective-C I use -[NSURL URLByDeletingLastPathComponent] to get parent URL. What\'s the equivalent of this in Java?

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-11 16:23

    The simple solution offered by Guava library.

    Code:

    URL url = new URL("https://www.ibm.watson.co.uk");
    String host = url.getHost();
    
    InternetDomainName parent = InternetDomainName.from(host).parent(); // returns ibm.watson.co.uk
    System.out.println("Immediate ancestor: "+parent);
    
    
    ImmutableList parts = InternetDomainName.from(host).parts(); 
    System.out.println("Individual components:  "+parts);
    
    
    InternetDomainName name = InternetDomainName.from(host).topPrivateDomain(); // watson.co.uk
    System.out.println("Top private domain - " + name);
    

    Output:

    Immediate ancestor: ibm.watson.co.uk
    
    Individual components:  [www, ibm, watson, co, uk]
    
    Top private domain - watson.co.uk
    

    For reference: https://guava.dev/releases/snapshot/api/docs/com/google/common/net/InternetDomainName.html

    Dependency required:

    https://mvnrepository.com/artifact/com.google.guava/guava

    I'm using version 19.0

    
            com.google.guava
            guava
    
    

    And, many more related functionalities are provided by this class InternetDomainName.

提交回复
热议问题