String urlString = "https://www.example.com:8080/path/to/resource"; URL url = new URL(urlString); String authority = url.getAuthority(); System.out.println(authority); // prints "www.example.com:8080"
URL url = new URL("https", "www.example.com", 8080, "/path/to/resource"); String authority = url.getAuthority(); System.out.println(authority); // prints "www.example.com:8080"
URL url = new URL("https://www.example.com"); String authority = url.getAuthority(); System.out.println(authority); // prints "www.example.com"This example creates a URL object with no path or port number, which means the authority component is just the hostname. The getAuthority() method is used to retrieve the authority, which is printed to the console. Package library: java.net.URL