Java : URL with Examples

URL (Java SE 21 & JDK 21) with Examples.
You will find code examples on most URL methods.


Summary

Class URL represents a Uniform Resource Locator, a pointer to a "resource" on the World Wide Web. A resource can be something as simple as a file or a directory, or it can be a reference to a more complicated object, such as a query to a database or to a search engine.

Class diagram

final var url = URI.create("https://example.com/java/index.html").toURL();
System.out.println(url); // "https://example.com/java/index.html"
System.out.println(url.getProtocol()); // "https"
System.out.println(url.getHost()); // "example.com"
System.out.println(url.getPath()); // "/java/index.html"

Constructors

URL (String spec)

Deprecated. Use URI.toURL() to construct an instance of URL.

Deprecated.

URL (String protocol, String host, int port, String file)

Deprecated. Use URI.toURL() to construct an instance of URL.

Deprecated.

URL (String protocol, String host, int port, String file, URLStreamHandler handler)

Deprecated. Use of(URI, URLStreamHandler) to construct an instance of URL associated with a custom protocol handler.

Deprecated.

URL (String protocol, String host, String file)

Deprecated. Use URI.toURL() to construct an instance of URL.

Deprecated.

URL (URL context, String spec)

Deprecated. Use URI.toURL() to construct an instance of URL.

Deprecated.

URL (URL context, String spec, URLStreamHandler handler)

Deprecated. Use of(URI, URLStreamHandler) to construct an instance of URL associated with a custom protocol handler.

Deprecated.

Methods

boolean equals (Object obj)

Compares this URL for equality with another object.

final var url1 = URI.create("http://example.com/docs/resource1.html").toURL();
final var url2 = URI.create("http://example.com/docs/resource1.html").toURL();

System.out.println(url1.equals(url2)); // true
// Two URLs with hosts are compared case-insensitively.
final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("HTTP://EXAMPLE.COM/").toURL();

System.out.println(url1.equals(url2)); // true
final var url1 = URI.create("http://example.com/a").toURL();
final var url2 = URI.create("http://example.com/b").toURL();

System.out.println(url1.equals(url2)); // false
// True if the IP addresses are equal.
final var url1 = URI.create("http://example.com").toURL();
final var url2 = URI.create("http://www.example.com").toURL();

System.out.println(url1.equals(url2)); // true

String getAuthority ()

Gets the authority part of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getAuthority()); // "www.example.com"
System.out.println(url1.getHost()); // "www.example.com"

final var url2 = URI.create("http://user-a@example.com:80/").toURL();
System.out.println(url2.getAuthority()); // "user-a@example.com:80"
System.out.println(url2.getHost()); // "example.com"

final var url3 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url3.getAuthority()); // "example.com"
System.out.println(url3.getHost()); // "example.com"

final var url4 = URI.create("file:///~/calendar").toURL();
System.out.println(url4.getAuthority()); // ""
System.out.println(url4.getHost()); // ""

final var url5 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url5.getAuthority()); // null
System.out.println(url5.getHost()); // ""

final Object getContent ()

Gets the contents of this URL.

final var url = URI.create("http://example.com").toURL();
final var content = url.getContent();

if (content instanceof InputStream is) {
    try (final var reader = new BufferedReader(
            new InputStreamReader(is))) {
        reader.lines().forEach(System.out::println);
    }
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>

final Object getContent (Class<?>[] classes)

Gets the contents of this URL.

final var url = URI.create("http://example.com").toURL();
final Class<?>[] classes = {InputStream.class};

final var content = url.getContent(classes);
if (content instanceof InputStream is) {
    try (final var reader = new BufferedReader(
            new InputStreamReader(is))) {
        reader.lines().forEach(System.out::println);
    }
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>

int getDefaultPort ()

Gets the default port number of the protocol associated with this URL.

final var uri1 = URI.create("http://example.com/").toURL();
System.out.println(uri1.getDefaultPort()); // 80
System.out.println(uri1.getPort()); // -1

final var uri2 = URI.create("http://example.com:9999/").toURL();
System.out.println(uri2.getDefaultPort()); // 80
System.out.println(uri2.getPort()); // 9999

final var uri3 = URI.create("https://example.com/").toURL();
System.out.println(uri3.getDefaultPort()); // 443
System.out.println(uri3.getPort()); // -1

final var uri4 = URI.create("ftp://example.com/").toURL();
System.out.println(uri4.getDefaultPort()); // 21
System.out.println(uri4.getPort()); // -1

final var uri5 = URI.create("file:///~/calendar").toURL();
System.out.println(uri5.getDefaultPort()); // -1
System.out.println(uri5.getPort()); // -1

final var uri6 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(uri6.getDefaultPort()); // -1
System.out.println(uri6.getPort()); // -1

String getFile ()

Gets the file name of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getFile()); // "/docs/resource1.html"
System.out.println(url1.getPath()); // "/docs/resource1.html"

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.getFile()); // "/index.html?query"
System.out.println(url2.getPath()); // "/index.html"

final var url3 = URI.create("http://user-a@example.com:80/").toURL();
System.out.println(url3.getFile()); // "/"
System.out.println(url3.getPath()); // "/"

final var url4 = URI.create("file:///~/calendar").toURL();
System.out.println(url4.getFile()); // "/~/calendar"
System.out.println(url4.getPath()); // "/~/calendar"

final var url5 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url5.getFile()); // "file:/home/xxx/sample.jar!/sample.txt"
System.out.println(url5.getPath()); // "file:/home/xxx/sample.jar!/sample.txt"

String getHost ()

Gets the host name of this URL, if applicable.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getAuthority()); // "www.example.com"
System.out.println(url1.getHost()); // "www.example.com"

final var url2 = URI.create("http://user-a@example.com:80/").toURL();
System.out.println(url2.getAuthority()); // "user-a@example.com:80"
System.out.println(url2.getHost()); // "example.com"

final var url3 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url3.getAuthority()); // "example.com"
System.out.println(url3.getHost()); // "example.com"

final var url4 = URI.create("file:///~/calendar").toURL();
System.out.println(url4.getAuthority()); // ""
System.out.println(url4.getHost()); // ""

final var url5 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url5.getAuthority()); // null
System.out.println(url5.getHost()); // ""

String getPath ()

Gets the path part of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getFile()); // "/docs/resource1.html"
System.out.println(url1.getPath()); // "/docs/resource1.html"

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.getFile()); // "/index.html?query"
System.out.println(url2.getPath()); // "/index.html"

final var url3 = URI.create("http://user-a@example.com:80/").toURL();
System.out.println(url3.getFile()); // "/"
System.out.println(url3.getPath()); // "/"

final var url4 = URI.create("file:///~/calendar").toURL();
System.out.println(url4.getFile()); // "/~/calendar"
System.out.println(url4.getPath()); // "/~/calendar"

final var url5 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url5.getFile()); // "file:/home/xxx/sample.jar!/sample.txt"
System.out.println(url5.getPath()); // "file:/home/xxx/sample.jar!/sample.txt"

int getPort ()

Gets the port number of this URL.

final var uri1 = URI.create("http://example.com/").toURL();
System.out.println(uri1.getDefaultPort()); // 80
System.out.println(uri1.getPort()); // -1

final var uri2 = URI.create("http://example.com:9999/").toURL();
System.out.println(uri2.getDefaultPort()); // 80
System.out.println(uri2.getPort()); // 9999

final var uri3 = URI.create("https://example.com/").toURL();
System.out.println(uri3.getDefaultPort()); // 443
System.out.println(uri3.getPort()); // -1

final var uri4 = URI.create("ftp://example.com/").toURL();
System.out.println(uri4.getDefaultPort()); // 21
System.out.println(uri4.getPort()); // -1

final var uri5 = URI.create("file:///~/calendar").toURL();
System.out.println(uri5.getDefaultPort()); // -1
System.out.println(uri5.getPort()); // -1

final var uri6 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(uri6.getDefaultPort()); // -1
System.out.println(uri6.getPort()); // -1

String getProtocol ()

Gets the protocol name of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getProtocol()); // "http"

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.getProtocol()); // "https"

final var url3 = URI.create("file:///~/calendar").toURL();
System.out.println(url3.getProtocol()); // "file"

final var url4 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url4.getProtocol()); // "jar"

String getQuery ()

Gets the query part of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getQuery()); // null

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.getQuery()); // "query"

final var url3 = URI.create("https://example.com/index.html?aaa&bbb&ccc").toURL();
System.out.println(url3.getQuery()); // "aaa&bbb&ccc"

final var url4 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url4.getQuery()); // null

String getRef ()

Gets the anchor (also known as the "reference") of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.getRef()); // null

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.getRef()); // "fragment"

final var url3 = URI.create("https://example.com/#aaaa").toURL();
System.out.println(url3.getRef()); // "aaaa"

final var url4 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url4.getRef()); // null

String getUserInfo ()

Gets the userInfo part of this URL.

final var url1 = URI.create("http://example.com/").toURL();
System.out.println(url1.getUserInfo()); // null

final var url2 = URI.create("http://user-a@example.com:80/").toURL();
System.out.println(url2.getUserInfo()); // "user-a"

int hashCode ()

Creates an integer suitable for hash table indexing.

final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("http://example.com/").toURL();

System.out.println(url1.hashCode()); // 1575608341
System.out.println(url2.hashCode()); // 1575608341
// Two URLs with hosts are compared case-insensitively.
final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("HTTP://EXAMPLE.COM/").toURL();

System.out.println(url1.hashCode()); // 1575608341
System.out.println(url2.hashCode()); // 1575608341
final var url1 = URI.create("http://example.com/a").toURL();
final var url2 = URI.create("http://example.com/b").toURL();

System.out.println(url1.hashCode()); // 1575609848
System.out.println(url2.hashCode()); // 1575609849
final var url1 = URI.create("http://example.com").toURL();
final var url2 = URI.create("http://www.example.com").toURL();

System.out.println(url1.equals(url2)); // true
System.out.println(url1.hashCode()); // 1575608294
System.out.println(url2.hashCode()); // 1575608294

static URL of (URI uri, URLStreamHandler handler)

Creates a URL from a URI, as if by invoking uri.toURL(), but associating it with the given URLStreamHandler, if allowed.

class DummyURLStreamHandler extends URLStreamHandler {
    @Override
    protected URLConnection openConnection(URL u) {
        System.out.println("dummy : openConnection url = " + u);
        return new URLConnection(u) {
            @Override
            public void connect() {
                System.out.println("dummy : connect!");
            }
        };
    }
}

final var url = URL.of(new URI("http://example.com"),
        new DummyURLStreamHandler());
System.out.println(url); // "http://example.com"

final var connection = url.openConnection();
connection.connect();

// Result
// ↓
//dummy : openConnection url = http://example.com
//dummy : connect!

URLConnection openConnection ()

Returns a URLConnection instance that represents a connection to the remote object referred to by the URL.

final var url = URI.create("http://example.com").toURL();

final var connection = url.openConnection();
try (final var reader = new BufferedReader(
        new InputStreamReader(connection.getInputStream()))) {
    reader.lines().forEach(System.out::println);
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>

URLConnection openConnection (Proxy proxy)

Same as openConnection(), except that the connection will be made through the specified proxy; Protocol handlers that do not support proxying will ignore the proxy parameter and make a normal connection.

final var url = URI.create("http://example.com").toURL();
final var proxy = new Proxy(Proxy.Type.HTTP,
        new InetSocketAddress("proxy.example.com", 8080));

final var connection = url.openConnection(proxy);
try (final var reader = new BufferedReader(
        new InputStreamReader(connection.getInputStream()))) {
    reader.lines().forEach(System.out::println);
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>

final InputStream openStream ()

Opens a connection to this URL and returns an InputStream for reading from that connection.

final var url = URI.create("http://example.com").toURL();
try (final var reader = new BufferedReader(
        new InputStreamReader(url.openStream()))) {
    reader.lines().forEach(System.out::println);
}

// Result
// ↓
//<!doctype html>
//<html>
//<head>
//    <title>Example Domain</title>
// ...
//</html>

boolean sameFile (URL other)

Compares two URLs, excluding the fragment component.

final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("http://example.com/").toURL();

System.out.println(url1.sameFile(url2)); // true
// Compares two URLs, excluding the fragment component.
final var url1 = URI.create("http://example.com/#aaa").toURL();
final var url2 = URI.create("http://example.com/#bbb").toURL();

System.out.println(url1.sameFile(url2)); // true
final var url1 = URI.create("http://example.com/?aaa").toURL();
final var url2 = URI.create("http://example.com/?bbb").toURL();

System.out.println(url1.sameFile(url2)); // false
// Two URLs with hosts are compared case-insensitively.
final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("HTTP://EXAMPLE.COM/").toURL();

System.out.println(url1.sameFile(url2)); // true
final var url1 = URI.create("http://example.com/a").toURL();
final var url2 = URI.create("http://example.com/b").toURL();

System.out.println(url1.sameFile(url2)); // false
// True if the IP addresses are equal.
final var url1 = URI.create("http://example.com/").toURL();
final var url2 = URI.create("http://www.example.com/").toURL();

System.out.println(url1.sameFile(url2)); // true

static void setURLStreamHandlerFactory (URLStreamHandlerFactory fac)

Sets an application's URLStreamHandlerFactory.

class DummyURLStreamHandler extends URLStreamHandler {
    @Override
    protected URLConnection openConnection(URL u) {
        System.out.println("dummy : openConnection url = " + u);
        return new URLConnection(u) {
            @Override
            public void connect() {
                System.out.println("dummy : connect!");
            }
        };
    }
}

URL.setURLStreamHandlerFactory(protocol -> {
    System.out.println("createURLStreamHandler! : " + protocol);
    return new DummyURLStreamHandler();
});

final var url = URI.create("http://example.com/").toURL();
final var connection = url.openConnection();
connection.connect();

// Result
// ↓
//createURLStreamHandler! : http
//dummy : openConnection url = http://example.com/
//dummy : connect!

String toExternalForm ()

Constructs a string representation of this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.toExternalForm()); // "http://www.example.com/docs/resource1.html"

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.toExternalForm()); // "https://example.com/index.html?query#fragment"

final var url3 = URI.create("file:///~/calendar").toURL();
System.out.println(url3.toExternalForm()); // "file:/~/calendar"

final var url4 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url4.toExternalForm()); // "jar:file:/home/xxx/sample.jar!/sample.txt"

URI toURI ()

Returns a URI equivalent to this URL.

final var url1 = URI.create("http://www.example.com/docs/resource1.html").toURL();
System.out.println(url1.toURI()); // "http://www.example.com/docs/resource1.html"

final var url2 = URI.create("https://example.com/index.html?query#fragment").toURL();
System.out.println(url2.toURI()); // "https://example.com/index.html?query#fragment"

final var url3 = URI.create("file:///~/calendar").toURL();
System.out.println(url3.toURI()); // "file:/~/calendar"

final var url4 = URI.create("jar:file:/home/xxx/sample.jar!/sample.txt").toURL();
System.out.println(url4.toURI()); // "jar:file:/home/xxx/sample.jar!/sample.txt"
// Escape.
final var url = URI.create("http://example.com/a%20b%20c/").toURL();
System.out.println(url.toURI()); // "http://example.com/a%20b%20c/"
System.out.println(url.toURI().getPath()); // "/a b c/"

Related posts

To top of page