Java URL Class
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
| Part | Value in the example | URL method |
|---|---|---|
| Protocol (scheme) | https | getProtocol() |
| User info | asha:secret | getUserInfo() |
| Host | shop.example.com | getHost() |
| Port | 8443 | getPort() |
| Authority | asha:secret@shop.example.com:8443 | getAuthority() |
| Path | /products/search | getPath() |
| Query | q=laptop&page=2 | getQuery() |
| File (path + query) | /products/search?q=laptop&page=2 | getFile() |
| Reference (fragment) | reviews | getRef() |
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 aURLwith a protocol handler.- A
file:URL has an empty host; its path is the location of the file on the local disk. toURL()declaresMalformedURLException, 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. UseURI.create(...).toURL()in new code. The Java URI class lesson explainsURIin 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, ornullwhen the part is missing (getQuery()on the second URL). getPort()returns-1when the URL has no explicit port.getDefaultPort()returns the standard port for the protocol:443forhttps,80forhttp.- 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.
| Problem | Example | Exception |
|---|---|---|
| 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/42is a valid relative URI, but aURLmust be absolute, sotoURL()throwsIllegalArgumentException.gopherxis valid syntax, but Java has no handler for it, sotoURL()throwsMalformedURLException.- 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:
URLEncoderturns spaces into+,&into%26and,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.decodeturns+back into spaces and%xxback 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 afile:URL.openStream()returns raw bytes, so the code wraps it in anInputStreamReaderwith UTF-8 and aBufferedReaderto 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.
| Method | Purpose |
|---|---|
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 asgetResponseCode().setRequestProperty("Accept-Language", "ta-IN")adds a header; the server echoes it back in the JSON.- For status codes 400 and above,
getInputStream()throws anIOException, so the body must be read fromgetErrorStream(). disconnect()tells Java this connection is no longer needed.
Note:
HttpURLConnectionis 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 (#setupvs#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, soExample.comequalsexample.com.- Because
URL.equals()andURL.hashCode()may use DNS, avoidURLobjects as keys in aHashMaporHashSet; useURIinstead.
Real-World Example: A Simple Link Checker
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:
- Validating first.
URI.create(link).toURL()rejectshtp//localhost/typo, which has no scheme, before any network call is made. - HEAD requests.
setRequestMethod("HEAD")asks the server for the status and headers only. The server answers withsendResponseHeaders(status, -1), meaning "no body". - Redirects.
setInstanceFollowRedirects(false)stops Java from following the301automatically, so the checker can report where/blogmoved to, using theLocationheader. - Broken and unreachable links. Codes 400 and above (
404,410) are reported as broken. A port with no server throwsConnectException, which is caught and reported as an error. - Clean up. The
finallyblock callsdisconnect()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.