Get root domain from request

前端 未结 4 1672
青春惊慌失措
青春惊慌失措 2021-01-31 03:07

Consider the below URL as an example. http://www.test1.example.com

Is there any method by which I can get \"example.com\" as an output. I know there is

相关标签:
4条回答
  • 2021-01-31 03:26
    import java.net.InetAddress;
    
    void Func() {
        InetAddress ia = InetAddress.getLocalHost();
        System.out.println (ia.getHostName());
    }
    

    Hope this helps.

    0 讨论(0)
  • 2021-01-31 03:27

    You can do this as a simple String manipulation:

    String A = "http://www.test1.example.com";
    String B = A.substring(A.lastIndexOf('.', A.lastIndexOf('.')-1) + 1);
    

    There is no standard way obtain example.com from a.b.c.example.com because such a transformation is generally not useful. There are TLDs that don't allow registrations on the second level; for example all .uk domains. Given news.bbc.co.uk you'd want to end up with bbc.co.uk, right?

    0 讨论(0)
  • 2021-01-31 03:37

    In HttpServletRequest, you can get individual parts of the URI using the methods below. You could also use them to reconstruct the URL piece by piece (to help debugging, or other tasks), like this:

    // Example: http://myhost:8080/people?lastname=Fox&age=30
    
    String uri = request.getScheme() + "://" +   // "http" + "://
                 request.getServerName() +       // "myhost"
                 ":" + request.getServerPort() + // ":" + "8080"
                 request.getRequestURI() +       // "/people"
                (request.getQueryString() != null ? "?" +
                 request.getQueryString() : ""); // "?" + "lastname=Fox&age=30"
    

    So request.getServerName() is the closest we got to you need.

    The "root domain":

    For the "root domain", you'll have to work through the String returned from getServerName(). This is necessary because the Servlet would have no way of knowing ahead of time what you call "host" or what is just a domain like .com (it could be a machine called com in your network - and not just a suffix -, who knows?).

    For the pattern you gave (one third+secondlevel+com/net), the following should get what you need:

    String domain = request.getServerName().replaceAll(".*\\.(?=.*\\.)", "");
    

    The above will give the following input/outputs:

    www.test.com       -> test.com
    test1.example.com  -> example.com
    a.b.c.d.e.f.g.com  -> g.com
    www.com            -> www.com
    com                -> com
    
    0 讨论(0)
  • 2021-01-31 03:40

    We have more reliable way of doing the same. There is google library "guava". Add following dependency in your pom.

    <dependency>
         <groupId>com.google.guava</groupId>
         <artifactId>guava</artifactId>
         <version>19.0</version>
    </dependency>
    

    Then try

    InternetDomainName.from("subdomain.example.co.in").topPrivateDomain().toString()
    

    This will give you "example.co.in"

    0 讨论(0)
提交回复
热议问题