URIs, URLs and URLConnection in Java: Retrieving Web Data and Headers
Web addresses and resource fetching: URI syntax, resolving, relativizing, normalizing and encoding, why URL constructors are deprecated, openStream, URLConnection and HttpURLConnection, request and response headers, conditional requests, Basic authentication, file: and jar: URLs.
kvi5hnuCode Sprout team member9 min readOn this page
Speaking HTTP over raw sockets, as in article 48, is instructive but impractical. You'd have to format requests, parse status lines and headers, handle redirects, chunked bodies and TLS, and so on. The Java library does all of this for you. This article covers the older, but still widely used, API built around URL and URLConnection. Article 53 introduces the modern HttpClient. Both start from the same thing: an address.
URIs and URLs
The java.net package distinguishes two kinds of addresses:
- A URI (Uniform Resource Identifier) is any string that follows the generic URI syntax of RFC 3986. The
java.net.URIclass only parses such strings. It has no methods to access the resource. - A URL (Uniform Resource Locator) is a URI that tells you how to locate a resource, such as
https://...orfile:.... Thejava.net.URLclass can open a connection, but only for schemes it has a handler for:http,https,file,jar,ftpand (send-only)mailtoin the JDK.
A URI like mailto:someone@example.com identifies something but can't be "opened". Identifiers that name a resource without locating it, such as urn:isbn:9780135328781, are traditionally called URNs.
The parts of a URI
The general form is
[scheme:]scheme-specific-part[#fragment]
A URI with a scheme is absolute, and one without is relative. An absolute URI whose scheme-specific part doesn't start with / is opaque, like mailto:someone@example.com. All others are hierarchical, with this structure:
[//authority][path][?query] authority = [user-info@]host[:port]
URI breaks a string into these parts:
| Method | For https://ada:pw@docs.example.com:8443/api/Socket.html?lang=en#connect() |
|---|---|
getScheme() | https |
getAuthority() | ada:pw@docs.example.com:8443 |
getUserInfo(), getHost(), getPort() | ada:pw, docs.example.com, 8443 (-1 if absent) |
getPath() | /api/Socket.html |
getQuery() | lang=en |
getFragment() | connect() |
getSchemeSpecificPart() | everything between the scheme and the fragment |
The getRaw... variants return the parts with percent-escapes, and the plain getters decode them.
Resolving, relativizing, normalizing
Web pages are full of relative links. Combining a base URI with a relative one is called resolving:
var base = URI.create("https://docs.example.com/api/java/nio/file/Files.html");
base.resolve("Path.html"); // https://docs.example.com/api/java/nio/file/Path.html
base.resolve("../../java/net/Socket.html#Socket()");
The relative path is interpreted against the base's directory, so ../.. climbs from /api/java/nio/file/ to /api/java/. The opposite operation, relativizing, computes the relative form:
URI.create("https://docs.example.com/api/").relativize(
URI.create("https://docs.example.com/api/java/lang/String.html")); // java/lang/String.html
normalize() removes . and .. segments. These operations work purely on strings and never contact a server.
Characters that need encoding
URIs may contain only a limited set of ASCII characters. Everything else, including spaces and non-ASCII letters, must be percent-encoded as % followed by two hex digits per UTF-8 byte. The single-argument constructor (and URI.create) requires an already-encoded string and rejects a space with a URISyntaxException. The multi-argument constructors take the unencoded components and quote illegal characters for you:
var uri = new URI("https", "example.com", "/search results/ü.html", "q=café & tea", null);
uri.toASCIIString(); // https://example.com/search%20results/%C3%BC.html?q=caf%C3%A9%20&%20tea
toString() leaves non-ASCII letters as they are, while toASCIIString() encodes them as well. Note that the constructor can't know that & inside the query was meant as data rather than as a separator. For query parameters, encode each name and value separately with URLEncoder, which article 52 covers.
Reading a resource
The simplest way to fetch a resource is URL.openStream():
try (InputStream in = URI.create("https://example.com/").toURL().openStream()) {
String html = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
That's enough for a quick download. For anything more, such as headers, timeouts, status codes or sending data, use a URLConnection.
URLConnection
A URLConnection goes through a fixed sequence of steps, and the order matters:
- Create it with
url.openConnection(). ForhttpandhttpsURLs, the object is anHttpURLConnection(orHttpsURLConnection), and you can cast it to get the HTTP-specific methods. - Configure it before connecting:
setConnectTimeout,setReadTimeout,setRequestProperty(name, value)for request headers,setDoOutput(true)to send a body (article 52),setIfModifiedSince,setUseCaches, and for HTTP,setRequestMethodandsetInstanceFollowRedirects. - Connect with
connect(), or implicitly by calling any method that needs the response, such asgetInputStreamorgetResponseCode. This sends the request and reads the response headers. - Query the response headers.
- Read the body with
getInputStream().
Setting a request property after connecting throws an IllegalStateException. Without timeouts, both connecting and reading can block indefinitely, so always set them.
Response headers
getHeaderFields() returns all headers as a Map<String, List<String>>, since a header may occur several times. The status line, such as HTTP/1.1 200 OK, is stored under the key null. There's also an older iteration style: getHeaderFieldKey(n) and getHeaderField(n) for n = 1, 2, ... until null is returned, with getHeaderField(0) giving the status line. Header names are case-insensitive in HTTP, so look them up with getHeaderField(name) rather than in the map.
Convenience methods convert the common headers:
| Method | Header | Result |
|---|---|---|
getContentType() | Content-Type | String |
getContentLengthLong() | Content-Length | long, -1 if unknown |
getContentEncoding() | Content-Encoding | String |
getDate(), getExpiration(), getLastModified() | Date, Expires, Last-Modified | long milliseconds since the epoch, 0 if unknown |
getHeaderFieldInt, getHeaderFieldLong, getHeaderFieldDate | any | parsed values with a default |
HTTP specifics
HttpURLConnection adds getResponseCode() and getResponseMessage(). For status codes of 400 and above, getInputStream() throws an IOException (a FileNotFoundException for 404), and the server's error page is available from getErrorStream(). By default, redirects to the same protocol are followed automatically. Redirects from http to https or the reverse are not.
A conditional request saves bandwidth. With setIfModifiedSince(millis), the connection sends an If-Modified-Since header, and an unchanged resource comes back as 304 Not Modified with no body.
Password-protected pages often use HTTP Basic authentication. The client sends the user name and password, joined by a colon and Base64-encoded:
String credentials = Base64.getEncoder().encodeToString(
(user + ":" + password).getBytes(StandardCharsets.UTF_8));
connection.setRequestProperty("Authorization", "Basic " + credentials);
Base64 is an encoding, not encryption, so only send credentials over HTTPS. Alternatively, install a java.net.Authenticator that supplies credentials when the server asks for them with a 401 response.
Other URL schemes
file: URLs read local files. Get them from path.toUri().toURL() instead of building strings. jar: URLs address an entry inside a JAR or zip file, with !/ separating the archive from the entry:
jar:file:/home/ada/lib.jar!/config/app.properties
This is how resources on the class path are reached, for example by Class.getResource. The connection is a JarURLConnection, which also gives access to the JarFile and its manifest. For a scheme with no handler at all, toURL() already fails with a MalformedURLException (unknown protocol). Some handlers support only one direction: the JDK's mailto: handler can only send, so openStream() on a mailto: URL throws an UnknownServiceException.
The program
The demo parses, resolves, relativizes and encodes URIs. It then starts the JDK's built-in HTTP server (com.sun.net.httpserver, covered in article 55) on the loopback interface and talks to it: it reads a page with openStream, inspects the response headers of a URLConnection (leaving out the ever-changing Date), makes a conditional request that returns 304, tries a protected page without and with Basic credentials, and requests a missing page. Finally, it reads a file: URL and an entry from a jar: URL built in a temporary directory.
import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.jar.*;
public class Solution {
static final Instant MODIFIED = Instant.parse("2026-01-02T03:04:05Z");
static HttpServer startServer() throws IOException {
HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
server.createContext("/page.html", exchange -> {
byte[] body = "<html><body>Hello from the loopback server</body></html>".getBytes(StandardCharsets.UTF_8);
Headers h = exchange.getResponseHeaders();
h.set("Content-Type", "text/html; charset=UTF-8");
h.set("Last-Modified", DateTimeFormatter.RFC_1123_DATE_TIME.format(MODIFIED.atZone(ZoneOffset.UTC)));
h.set("X-Agent-Seen", String.valueOf(exchange.getRequestHeaders().getFirst("User-Agent")));
String since = exchange.getRequestHeaders().getFirst("If-Modified-Since");
if (since != null && !ZonedDateTime.parse(since, DateTimeFormatter.RFC_1123_DATE_TIME).toInstant().isBefore(MODIFIED)) {
exchange.sendResponseHeaders(304, -1); // not modified, no body
} else {
exchange.sendResponseHeaders(200, body.length);
exchange.getResponseBody().write(body);
}
exchange.close();
});
server.createContext("/secret", exchange -> {
String auth = exchange.getRequestHeaders().getFirst("Authorization");
String expected = "Basic " + Base64.getEncoder().encodeToString("ada:s3cret".getBytes(StandardCharsets.UTF_8));
byte[] body = (expected.equals(auth) ? "the secret is 42" : "who are you?").getBytes(StandardCharsets.UTF_8);
if (!expected.equals(auth)) exchange.getResponseHeaders().set("WWW-Authenticate", "Basic realm=\"demo\"");
exchange.sendResponseHeaders(expected.equals(auth) ? 200 : 401, body.length);
exchange.getResponseBody().write(body);
exchange.close();
});
server.start();
return server;
}
public static void main(String[] args) throws Exception {
System.out.println("--- parsing URIs ---");
var uri = new URI("https://ada:pw@docs.example.com:8443/api/java/net/Socket.html?lang=en&v=25#connect()");
System.out.println("scheme=" + uri.getScheme() + " userInfo=" + uri.getUserInfo() + " host=" + uri.getHost()
+ " port=" + uri.getPort() + "\n path=" + uri.getPath() + " query=" + uri.getQuery()
+ " fragment=" + uri.getFragment() + " authority=" + uri.getAuthority());
var mail = URI.create("mailto:someone@example.com");
System.out.println("mailto: absolute=" + mail.isAbsolute() + " opaque=" + mail.isOpaque()
+ " ssp=" + mail.getSchemeSpecificPart() + " path=" + mail.getPath());
var relative = URI.create("../../java/net/Socket.html#Socket()");
System.out.println("relative: absolute=" + relative.isAbsolute() + " opaque=" + relative.isOpaque());
System.out.println("--- resolving and relativizing ---");
var base = URI.create("https://docs.example.com/api/java/nio/file/Files.html");
System.out.println("resolve: " + base.resolve(relative));
System.out.println("resolve: " + base.resolve("Path.html"));
var root = URI.create("https://docs.example.com/api/");
System.out.println("relativize: " + root.relativize(URI.create("https://docs.example.com/api/java/lang/String.html")));
System.out.println("normalize: " + URI.create("https://example.com/a/./b/../c/x.html").normalize());
System.out.println("--- encoding with the multi-argument constructor ---");
var built = new URI("https", "example.com", "/search results/ü.html", "q=café & tea", null);
System.out.println("toString: " + built);
System.out.println("toASCIIString: " + built.toASCIIString());
System.out.println("getPath (decoded): " + built.getPath() + ", getRawQuery: " + built.getRawQuery());
try {
new URI("https://example.com/search results");
} catch (URISyntaxException e) {
System.out.println("single-argument constructor: " + e.getMessage());
}
HttpServer server = startServer();
String origin = "http://127.0.0.1:" + server.getAddress().getPort();
try {
System.out.println("--- URL.openStream ---");
URL url = URI.create(origin + "/page.html").toURL();
try (InputStream in = url.openStream()) {
System.out.println(new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
System.out.println("--- URLConnection and headers ---");
URLConnection connection = url.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(5000);
connection.setRequestProperty("User-Agent", "CoreJavaDemo/1.0");
connection.connect();
var interesting = new TreeMap<String, List<String>>();
connection.getHeaderFields().forEach((k, v) -> {
if (k == null || !k.equalsIgnoreCase("Date")) interesting.put(String.valueOf(k), v);
});
interesting.forEach((k, v) -> System.out.println(k + ": " + v));
System.out.println("getContentType: " + connection.getContentType()
+ ", getContentLength: " + connection.getContentLengthLong()
+ ", getLastModified: " + Instant.ofEpochMilli(connection.getLastModified())
+ ", getHeaderField(0): " + connection.getHeaderField(0));
connection.getInputStream().close();
System.out.println("--- conditional request ---");
var conditional = (HttpURLConnection) url.openConnection();
conditional.setIfModifiedSince(MODIFIED.toEpochMilli());
System.out.println("If-Modified-Since: " + conditional.getResponseCode() + " " + conditional.getResponseMessage());
conditional.disconnect();
System.out.println("--- authentication and errors ---");
var anonymous = (HttpURLConnection) URI.create(origin + "/secret").toURL().openConnection();
System.out.println("without credentials: " + anonymous.getResponseCode() + ", "
+ anonymous.getHeaderField("WWW-Authenticate"));
try {
anonymous.getInputStream();
} catch (IOException e) {
System.out.println("getInputStream: " + e.getClass().getSimpleName() + "; getErrorStream: "
+ new String(anonymous.getErrorStream().readAllBytes(), StandardCharsets.UTF_8));
}
var authorized = (HttpURLConnection) URI.create(origin + "/secret").toURL().openConnection();
authorized.setRequestProperty("Authorization",
"Basic " + Base64.getEncoder().encodeToString("ada:s3cret".getBytes(StandardCharsets.UTF_8)));
try (InputStream in = authorized.getInputStream()) {
System.out.println("with Basic credentials: " + authorized.getResponseCode() + " "
+ new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
var missing = (HttpURLConnection) URI.create(origin + "/nothing-here").toURL().openConnection();
System.out.println("missing page: " + missing.getResponseCode());
missing.disconnect();
} finally {
server.stop(0);
}
System.out.println("--- file: and jar: URLs ---");
Path dir = Files.createTempDirectory("urls");
Path text = dir.resolve("notes.txt");
Path jar = dir.resolve("lib.jar");
try {
Files.writeString(text, "local file content", StandardCharsets.UTF_8);
try (var out = new JarOutputStream(Files.newOutputStream(jar))) {
out.putNextEntry(new JarEntry("config/app.properties"));
out.write("greeting=hello from a jar".getBytes(StandardCharsets.UTF_8));
}
URL fileUrl = text.toUri().toURL();
System.out.println(fileUrl.getProtocol() + ": " + new String(fileUrl.openStream().readAllBytes(), StandardCharsets.UTF_8));
URL jarUrl = URI.create("jar:" + jar.toUri() + "!/config/app.properties").toURL();
var connection = (JarURLConnection) jarUrl.openConnection();
connection.setUseCaches(false); // so the jar file is released
try (InputStream in = connection.getInputStream()) {
System.out.println(jarUrl.getProtocol() + ": entry " + connection.getEntryName() + " -> "
+ new String(in.readAllBytes(), StandardCharsets.UTF_8));
}
try {
URI.create("mailto:someone@example.com").toURL().openStream();
} catch (IOException | IllegalArgumentException e) {
System.out.println("mailto: " + e.getClass().getSimpleName());
}
} finally {
Files.delete(text);
Files.delete(jar);
Files.delete(dir);
}
}
}
--- parsing URIs ---
scheme=https userInfo=ada:pw host=docs.example.com port=8443
path=/api/java/net/Socket.html query=lang=en&v=25 fragment=connect() authority=ada:pw@docs.example.com:8443
mailto: absolute=true opaque=true ssp=someone@example.com path=null
relative: absolute=false opaque=false
--- resolving and relativizing ---
resolve: https://docs.example.com/api/java/java/net/Socket.html#Socket()
resolve: https://docs.example.com/api/java/nio/file/Path.html
relativize: java/lang/String.html
normalize: https://example.com/a/c/x.html
--- encoding with the multi-argument constructor ---
toString: https://example.com/search%20results/ü.html?q=café%20&%20tea
toASCIIString: https://example.com/search%20results/%C3%BC.html?q=caf%C3%A9%20&%20tea
getPath (decoded): /search results/ü.html, getRawQuery: q=café%20&%20tea
single-argument constructor: Illegal character in path at index 26: https://example.com/search results
--- URL.openStream ---
<html><body>Hello from the loopback server</body></html>
--- URLConnection and headers ---
Content-length: [56]
Content-type: [text/html; charset=UTF-8]
Last-modified: [Fri, 2 Jan 2026 03:04:05 GMT]
X-agent-seen: [CoreJavaDemo/1.0]
null: [HTTP/1.1 200 OK]
getContentType: text/html; charset=UTF-8, getContentLength: 56, getLastModified: 2026-01-02T03:04:05Z, getHeaderField(0): HTTP/1.1 200 OK
--- conditional request ---
If-Modified-Since: 304 Not Modified
--- authentication and errors ---
without credentials: 401, Basic realm="demo"
getInputStream: IOException; getErrorStream: who are you?
with Basic credentials: 200 the secret is 42
missing page: 404
--- file: and jar: URLs ---
file: local file content
jar: entry config/app.properties -> greeting=hello from a jar
mailto: UnknownServiceException
Common questions
When should I use URI and when URL?
Use URI to store, compare, parse, resolve and build addresses; it is a pure value. Convert to a URL only at the moment you open a connection. In particular, never put URL objects in hash sets or maps: URL.equals and hashCode may perform DNS lookups and consider two hosts equal if they resolve to the same address.
Why does URI.create("http://example.com/a b") throw?
A space is illegal in a URI. Either encode it yourself (%20) or use a multi-argument constructor such as new URI("http", "example.com", "/a b", null), which encodes the components.
Should I still use URLConnection for new code?
For HTTP, prefer HttpClient (article 53). URLConnection remains useful for file: and jar: URLs, for class-path resources, and in older code bases and libraries that you maintain.
How do I read a resource from the class path?
getClass().getResourceAsStream("/config/app.properties") (leading / means from the root of the class path), or getResource(...) for a URL. Inside a JAR, the result is a jar: URL, so don't try to turn it into a File; read it as a stream.
How do I download a large file to disk?
try (InputStream in = url.openStream()) { Files.copy(in, target, StandardCopyOption.REPLACE_EXISTING); } with a URLConnection that has timeouts, or more simply HttpClient with BodyHandlers.ofFile(target), which streams without holding the body in memory.
API reference
| API | Purpose |
|---|---|
new URI(text), URI.create(text) | parse an encoded URI |
new URI(scheme, host, path, query, fragment) and other multi-argument constructors | build a URI from unencoded parts |
URI.getScheme(), getHost(), getPort(), getPath(), getQuery(), getFragment(), getRaw...() | components |
URI.isAbsolute(), isOpaque() | classification |
URI.resolve(uri), relativize(uri), normalize() | combine and simplify |
URI.toURL(), toASCIIString() | convert |
URL.openStream(), URL.openConnection() | access the resource |
URLConnection.setConnectTimeout, setReadTimeout, setRequestProperty, setIfModifiedSince | configure before connecting |
URLConnection.connect(), getInputStream() | send the request, read the body |
URLConnection.getHeaderFields(), getHeaderField(name), getContentType(), getContentLengthLong(), getLastModified() | response headers |
HttpURLConnection.getResponseCode(), getResponseMessage(), getErrorStream(), disconnect() | HTTP status and errors |
JarURLConnection.getEntryName(), getJarFile() | jar: URLs |
Summary
URIparses and manipulates identifiers.URLopens resources for supported schemes. Create URLs withURI.toURL(), since theURLconstructors are deprecated.- A hierarchical URI has a scheme, authority (user info, host, port), path, query and fragment.
resolve,relativizeandnormalizework on these parts without network access. - The multi-argument
URIconstructors percent-encode illegal characters. Query parameters still needURLEncoder. URLConnection: create, configure (timeouts, headers), connect, read headers, read the body, in that order.HttpURLConnectiongives status codes,getErrorStream()for error responses, and conditional requests. Basic authentication is a Base64 header and needs HTTPS.file:andjar:URLs reach local files and archive entries.
Practice Questions
What do getHost(), getPort() and getQuery() return for URI.create("http://example.com/a/b?x=1")?
example.com, -1 (no explicit port), and x=1. The default port 80 isn't filled in. Callers must apply the scheme's default themselves.
Resolve ../img/logo.png against https://example.com/docs/guide/index.html.
The base directory is /docs/guide/, and .. moves up to /docs/, so the result is https://example.com/docs/img/logo.png.
Why does URI.create("https://example.com/my file.txt") throw, and how do you build that URI correctly?
The single-argument form expects an already-encoded URI, and a space isn't allowed. Use a multi-argument constructor, such as new URI("https", "example.com", "/my file.txt", null), which encodes the space as %20, or encode the string yourself.
A program calls connection.setRequestProperty(...) after connection.getResponseCode() and gets an exception. Why?
getResponseCode() connects and sends the request, so the request headers are already gone. Request properties must be set during the configuration step, before the connection is established. Afterwards, an IllegalStateException is thrown.
How do you read the body of a 404 or 500 response with HttpURLConnection?
getInputStream() throws an IOException for status codes of 400 and above. Check getResponseCode() first, and for error codes read getErrorStream(), which returns the server's error body (or null if there is none).
Previous: Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
Next: Posting Form Data in Java: GET and POST, URL Encoding and Multipart
Related reading
- Interruptible Sockets and TLS in Java: SocketChannel, Virtual Threads and SSLSocket
- Java Server Sockets: Serving Multiple Clients with Threads and Virtual Threads
- Java Sockets: Connecting to a Server, Timeouts and InetAddress
- XSL Transformations in Java: Stylesheets and the Transformer API
- Generating XML in Java: Building DOM Trees and Writing with Transformer, LSSerializer and StAX

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.