Java URL Class

Su Suriya Ravichandran Updated 18 Nov 2026
12 min read ·Lesson 202 of 306

The Java URL class (java.net.URL) represents a Uniform Resource Locator: the address of a resource such as a web page, an image or a file, together with the protocol needed to fetch it. Besides holding an address, a URL can open a connection and read the resource it points to.

This lesson shows how to create a URL the modern way, read each part of it, encode query values, read data from a URL, and use HttpURLConnection for simple HTTP calls.


The Parts of a URL

Every URL is made of parts, and the URL class has a getter for each one. Take this example:

https://asha:secret@shop.example.com:8443/products/search?q=laptop&page=2#reviews
PartValue in the exampleURL method
Protocol (scheme)httpsgetProtocol()
User infoasha:secretgetUserInfo()
Hostshop.example.comgetHost()
Port8443getPort()
Authorityasha:secret@shop.example.com:8443getAuthority()
Path/products/searchgetPath()
Queryq=laptop&page=2getQuery()
File (path + query)/products/search?q=laptop&page=2getFile()
Reference (fragment)reviewsgetRef()

The protocol tells Java how to fetch the resource. The JDK supports http, https, file, jar and ftp out of the box.


How to Create a URL in Java

Older code creates URLs with new URL("https://..."). Since Java 20 all URL constructors are deprecated, because they do not check the address strictly. The recommended way is to parse the text as a URI first and convert it with toURL().

Syntax:

URL url = URI.create("https://example.com/docs").toURL();   // recommended
URL old = new URL("https://example.com/docs");               // deprecated since Java 20
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class CreateUrl {
    public static void main(String[] args) throws MalformedURLException {
        URL docs = URI.create("https://docs.oracle.com/en/java/javase/21/").toURL();
        URL logo = URI.create("https://cdn.example.com/images/logo.png").toURL();
        URL localFile = URI.create("file:///tmp/report.txt").toURL();

        System.out.println(docs);
        System.out.println(logo.getProtocol() + " | " + logo.getHost() + " | " + logo.getPath());
        System.out.println(localFile.getProtocol() + " | host='" + localFile.getHost() + "' | " + localFile.getPath());
    }
}

Output:

https://docs.oracle.com/en/java/javase/21/
https | cdn.example.com | /images/logo.png
file | host='' | /tmp/report.txt

How it works:

  • URI.create(text) parses and validates the address. toURL() then turns it into a URL with a protocol handler.
  • A file: URL has an empty host; its path is the location of the file on the local disk.
  • toURL() declares MalformedURLException, which is thrown when Java has no handler for the protocol.

Note: You will still see new URL(...) in many tutorials and older projects. It works, but the compiler prints a deprecation warning. Use URI.create(...).toURL() in new code. The Java URI class lesson explains URI in depth.


Getting URL Parts with the Java URL Class

Once you have a URL, its getters split it into the parts from the table above.

import java.net.URI;
import java.net.URL;

public class UrlParts {
    public static void main(String[] args) throws Exception {
        URL url = URI.create(
                "https://asha:secret@shop.example.com:8443/products/search?q=laptop&page=2#reviews").toURL();

        System.out.println("Protocol : " + url.getProtocol());
        System.out.println("UserInfo : " + url.getUserInfo());
        System.out.println("Host     : " + url.getHost());
        System.out.println("Port     : " + url.getPort());
        System.out.println("Authority: " + url.getAuthority());
        System.out.println("Path     : " + url.getPath());
        System.out.println("Query    : " + url.getQuery());
        System.out.println("File     : " + url.getFile());
        System.out.println("Ref      : " + url.getRef());

        // When the port is missing, getPort() returns -1
        URL simple = URI.create("https://example.com/about").toURL();
        System.out.println("Port (not set): " + simple.getPort()
                + ", default port: " + simple.getDefaultPort());
        System.out.println("Query (not set): " + simple.getQuery());
    }
}

Output:

Protocol : https
UserInfo : asha:secret
Host     : shop.example.com
Port     : 8443
Authority: asha:secret@shop.example.com:8443
Path     : /products/search
Query    : q=laptop&page=2
File     : /products/search?q=laptop&page=2
Ref      : reviews
Port (not set): -1, default port: 443
Query (not set): null

How it works:

  • Each getter returns one part of the URL as a String, or null when the part is missing (getQuery() on the second URL).
  • getPort() returns -1 when the URL has no explicit port. getDefaultPort() returns the standard port for the protocol: 443 for https, 80 for http.
  • To find the port a connection will really use, write url.getPort() != -1 ? url.getPort() : url.getDefaultPort().

Handling Invalid URLs

Bad input fails in different places, so it is worth knowing which exception comes from where.

ProblemExampleException
Illegal characters or syntax"https://exa mple.com"IllegalArgumentException from URI.create()
No scheme (relative address)"/products/42"IllegalArgumentException from toURL()
Unknown protocol"gopherx://host/file"MalformedURLException from toURL()
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;

public class InvalidUrls {
    static void tryParse(String text) {
        try {
            URL url = URI.create(text).toURL();
            System.out.println("OK      " + text + " -> host " + url.getHost());
        } catch (IllegalArgumentException | MalformedURLException e) {
            System.out.println("INVALID " + text + " -> " + e.getClass().getSimpleName());
        }
    }

    public static void main(String[] args) {
        tryParse("https://example.com/products");
        tryParse("https://exa mple.com");
        tryParse("/products/42");
        tryParse("gopherx://host/file");
    }
}

Output:

OK      https://example.com/products -> host example.com
INVALID https://exa mple.com -> IllegalArgumentException
INVALID /products/42 -> IllegalArgumentException
INVALID gopherx://host/file -> MalformedURLException

How it works:

  • A space is not allowed in a URI, so URI.create() rejects the second address.
  • /products/42 is a valid relative URI, but a URL must be absolute, so toURL() throws IllegalArgumentException.
  • gopherx is valid syntax, but Java has no handler for it, so toURL() throws MalformedURLException.
  • One multi-catch handles all cases, which is a simple way to validate URLs typed by a user.

Building URLs with Encoded Query Parameters

Query values often contain spaces, &, = or non-English characters. These must be percent-encoded, or the URL breaks. URLEncoder.encode(value, StandardCharsets.UTF_8) does this, and URLDecoder.decode reverses it.

import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class EncodeQuery {
    public static void main(String[] args) throws Exception {
        String searchText = "java & spring boot";
        String city = "Chennai, Tamil Nadu";

        // Encode each value separately, then join the pairs with &
        String query = "q=" + URLEncoder.encode(searchText, StandardCharsets.UTF_8)
                + "&city=" + URLEncoder.encode(city, StandardCharsets.UTF_8);
        URL url = URI.create("https://jobs.example.com/search?" + query).toURL();

        System.out.println(url);
        System.out.println("Query  : " + url.getQuery());

        // Decoding turns the query values back into plain text
        for (String pair : url.getQuery().split("&")) {
            String[] keyValue = pair.split("=", 2);
            System.out.println(keyValue[0] + " = " + URLDecoder.decode(keyValue[1], StandardCharsets.UTF_8));
        }
    }
}

Output:

https://jobs.example.com/search?q=java+%26+spring+boot&city=Chennai%2C+Tamil+Nadu
Query  : q=java+%26+spring+boot&city=Chennai%2C+Tamil+Nadu
q = java & spring boot
city = Chennai, Tamil Nadu

How it works:

  • URLEncoder turns spaces into +, & into %26 and , into %2C, so the values cannot be confused with the separators of the query string.
  • Encode only the values (and keys if needed), never the whole URL; otherwise ://, / and ? would be encoded too.
  • URLDecoder.decode turns + back into spaces and %xx back into characters.

Reading Data from a URL with openStream()

url.openStream() connects to the resource and returns an InputStream with its content. It works for any supported protocol. This example reads a local file through a file: URL, so it runs without an internet connection.

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;

public class ReadFromUrl {
    public static void main(String[] args) throws Exception {
        // Create a small file and get its file: URL
        Path notes = Files.createTempFile("notes", ".txt");
        Files.write(notes, List.of("Buy milk", "Call the bank", "Finish Java lesson"));
        URL url = notes.toUri().toURL();
        System.out.println("Protocol: " + url.getProtocol());

        // openStream() works the same for file:, http: and https: URLs
        try (BufferedReader reader = new BufferedReader(
                new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) {
            String line;
            int number = 1;
            while ((line = reader.readLine()) != null) {
                System.out.println(number++ + ". " + line);
            }
        }
        Files.delete(notes);
    }
}

Output:

Protocol: file
1. Buy milk
2. Call the bank
3. Finish Java lesson

How it works:

  • Path.toUri().toURL() converts a file path into a file: URL.
  • openStream() returns raw bytes, so the code wraps it in an InputStreamReader with UTF-8 and a BufferedReader to read lines.
  • try-with-resources closes the stream, which also releases the connection.
  • With an https: URL, the same code downloads a web page instead.

Using HttpURLConnection for HTTP Requests

For http and https URLs, url.openConnection() returns an HttpURLConnection. It lets you choose the request method, add headers, set timeouts and read the status code. The example starts a small local server so it runs anywhere.

MethodPurpose
setRequestMethod("GET")Choose GET, POST, PUT, DELETE, HEAD, OPTIONS or TRACE
setRequestProperty(name, value)Add a request header
setConnectTimeout(ms), setReadTimeout(ms)Avoid waiting forever
getResponseCode()Send the request and read the status code
getHeaderField(name)Read a response header
getInputStream() / getErrorStream()Read the body of a success / error response
disconnect()Release the connection
import com.sun.net.httpserver.HttpServer;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.URI;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class HttpUrlConnectionDemo {
    public static void main(String[] args) throws Exception {
        // Local test server: /api/greeting returns JSON, everything else is 404
        HttpServer server = HttpServer.create(new InetSocketAddress("localhost", 8081), 0);
        server.createContext("/", exchange -> {
            boolean found = exchange.getRequestURI().getPath().equals("/api/greeting");
            String lang = exchange.getRequestHeaders().getFirst("Accept-Language");
            byte[] body = (found ? "{\"message\":\"Vanakkam\",\"lang\":\"" + lang + "\"}"
                                 : "{\"error\":\"not found\"}").getBytes(StandardCharsets.UTF_8);
            exchange.getResponseHeaders().add("Content-Type", "application/json");
            exchange.sendResponseHeaders(found ? 200 : 404, body.length);
            exchange.getResponseBody().write(body);
            exchange.close();
        });
        server.start();

        for (String path : new String[]{"/api/greeting", "/api/missing"}) {
            URL url = URI.create("http://localhost:8081" + path).toURL();
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Accept-Language", "ta-IN");
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);

            int status = connection.getResponseCode();           // sends the request
            InputStream bodyStream = status < 400 ? connection.getInputStream() : connection.getErrorStream();
            String body = new String(bodyStream.readAllBytes(), StandardCharsets.UTF_8);

            System.out.println(path + " -> " + status + " " + connection.getResponseMessage());
            System.out.println("  Content-Type: " + connection.getHeaderField("Content-Type"));
            System.out.println("  Body: " + body);
            connection.disconnect();
        }
        server.stop(0);
    }
}

Output:

/api/greeting -> 200 OK
  Content-Type: application/json
  Body: {"message":"Vanakkam","lang":"ta-IN"}
/api/missing -> 404 Not Found
  Content-Type: application/json
  Body: {"error":"not found"}

How it works:

  • openConnection() only creates the connection object. Nothing is sent until you call a method that needs the response, such as getResponseCode().
  • setRequestProperty("Accept-Language", "ta-IN") adds a header; the server echoes it back in the JSON.
  • For status codes 400 and above, getInputStream() throws an IOException, so the body must be read from getErrorStream().
  • disconnect() tells Java this connection is no longer needed.

Note: HttpURLConnection is an old API with a clumsy design. For new code, prefer the Java HttpClient, which supports HTTP/2, asynchronous calls and a cleaner builder style.


Comparing URLs: equals() and sameFile()

URL.equals() has a surprising behaviour: to compare two hosts it may resolve them with DNS, which can be slow and gives different answers depending on the network. For comparing addresses, convert to URI, which compares text only.

import java.net.URI;
import java.net.URL;

public class CompareUrls {
    public static void main(String[] args) throws Exception {
        URI first = URI.create("https://Example.com/docs/intro#setup");
        URI second = URI.create("https://example.com/docs/intro#install");

        URL firstUrl = first.toURL();
        URL secondUrl = second.toURL();

        // sameFile() ignores the #fragment
        System.out.println("sameFile(): " + firstUrl.sameFile(secondUrl));

        // URI comparison is pure text: no network access, host case ignored
        System.out.println("URI equal (with fragment)   : " + first.equals(second));
        URI firstNoFragment = URI.create(first.toString().split("#")[0]);
        URI secondNoFragment = URI.create(second.toString().split("#")[0]);
        System.out.println("URI equal (without fragment): " + firstNoFragment.equals(secondNoFragment));
    }
}

Output:

sameFile(): true
URI equal (with fragment)   : false
URI equal (without fragment): true

How it works:

  • sameFile() compares two URLs while ignoring the fragment (#setup vs #install), because both point to the same page.
  • URI.equals() compares the text of the addresses. It ignores the case of the scheme and host, so Example.com equals example.com.
  • Because URL.equals() and URL.hashCode() may use DNS, avoid URL objects as keys in a HashMap or HashSet; use URI instead.

Website owners need to find broken links. This link checker takes a list of addresses, rejects invalid ones, sends a HEAD request to each valid one and reports its status. HEAD asks only for the headers, not the body, so checking is fast. A local server stands in for the website.

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.List;
import java.util.Map;

public class LinkChecker {

    // Returns a short status line for one link
    static String check(String link) {
        URL url;
        try {
            url = URI.create(link).toURL();
        } catch (IllegalArgumentException | MalformedURLException e) {
            return "INVALID  (bad address)";
        }

        HttpURLConnection connection = null;
        try {
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("HEAD");              // headers only, no body
            connection.setInstanceFollowRedirects(false);     // report redirects instead of following
            connection.setConnectTimeout(2000);
            connection.setReadTimeout(2000);

            int code = connection.getResponseCode();
            if (code >= 300 && code < 400) {
                return "REDIRECT " + code + " -> " + connection.getHeaderField("Location");
            }
            return (code < 400 ? "OK       " : "BROKEN   ") + code;
        } catch (IOException e) {
            return "ERROR    " + e.getClass().getSimpleName();
        } finally {
            if (connection != null) connection.disconnect();
        }
    }

    public static void main(String[] args) throws Exception {
        // Fake website: path -> status code
        Map<String, Integer> pages = Map.of("/", 200, "/about", 200, "/blog", 301, "/old-offer", 410);
        HttpServer site = HttpServer.create(new InetSocketAddress("localhost", 8082), 0);
        site.createContext("/", exchange -> {
            String path = exchange.getRequestURI().getPath();
            int status = pages.getOrDefault(path, 404);
            if (status == 301) exchange.getResponseHeaders().add("Location", "/articles");
            exchange.sendResponseHeaders(status, -1);         // -1 = no body
            exchange.close();
        });
        site.start();

        List<String> links = List.of(
                "http://localhost:8082/",
                "http://localhost:8082/about",
                "http://localhost:8082/blog",
                "http://localhost:8082/old-offer",
                "http://localhost:8082/contact",
                "http://localhost:8099/",            // nothing listens on this port
                "htp//localhost/typo");

        int broken = 0;
        for (String link : links) {
            String result = check(link);
            if (!result.startsWith("OK") && !result.startsWith("REDIRECT")) broken++;
            System.out.printf("%-34s %s%n", link, result);
        }
        System.out.println(broken + " of " + links.size() + " links need attention");
        site.stop(0);
    }
}

Output:

http://localhost:8082/             OK       200
http://localhost:8082/about        OK       200
http://localhost:8082/blog         REDIRECT 301 -> /articles
http://localhost:8082/old-offer    BROKEN   410
http://localhost:8082/contact      BROKEN   404
http://localhost:8099/             ERROR    ConnectException
htp//localhost/typo                INVALID  (bad address)
4 of 7 links need attention

How it works:

  1. Validating first. URI.create(link).toURL() rejects htp//localhost/typo, which has no scheme, before any network call is made.
  2. HEAD requests. setRequestMethod("HEAD") asks the server for the status and headers only. The server answers with sendResponseHeaders(status, -1), meaning "no body".
  3. Redirects. setInstanceFollowRedirects(false) stops Java from following the 301 automatically, so the checker can report where /blog moved to, using the Location header.
  4. Broken and unreachable links. Codes 400 and above (404, 410) are reported as broken. A port with no server throws ConnectException, which is caught and reported as an error.
  5. Clean up. The finally block calls disconnect() for every link that opened a connection, even when an exception was thrown.

To check links on a live site, replace the local server with real https:// addresses. For the TCP connections underneath every URL, see Java networking basics; the same checks can be written with less code using Java HTTP requests and HttpClient.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java URL Class and get answers drawn from it.

Signed-in readers only.