Java URLConnection
Open connections to URLs in Java with URLConnection to read resources and send requests.
Java URLConnection
A URL names a resource; a URLConnection is the live link you open to actually read or write it. You never construct one directly — you call url.openConnection(), and Java returns a connection object whose concrete type depends on the protocol (http:, https:, file:, jar:, …). URLConnection is the protocol-agnostic base class; the next chapter covers its HTTP-specific subclass.
Opening and configuring
URL url = URI.create("http://example.com/data").toURL();
URLConnection conn = url.openConnection(); // not connected yet
conn.setConnectTimeout(2000); // ms to establish the connection
conn.setReadTimeout(2000); // ms to wait for data
conn.connect(); // optional; reading connects implicitlyopenConnection() does not touch the network — it just creates a configurable object. The actual connection happens lazily when you call connect() or, more commonly, when you first read from getInputStream(). Set timeouts before connecting; both default to 0, meaning "wait forever," which is rarely what you want.
Reading the response
Two kinds of information come back: headers (metadata) and the body (an input stream).
String type = conn.getContentType(); // e.g. "text/plain; charset=utf-8"
int length = conn.getContentLength(); // -1 if the server did not send it
long when = conn.getLastModified();
try (InputStream in = conn.getInputStream()) {
// read the body bytes
}Header getters like getContentType() are conveniences over the general getHeaderField("Name"). Always read the body through try-with-resources so the underlying socket is released.
Sending data
To send a request body, switch the connection into output mode with setDoOutput(true), then write to getOutputStream(). For HTTP this implies a POST. Because controlling the method, status code, and error stream needs HTTP-specific behaviour, that work belongs to HttpURLConnection — the subject of the next chapter.
A worked example: reading a resource over a connection
This program serves a small text body from a loopback HttpServer, opens a generic URLConnection to it, inspects the response headers, and streams the body line by line — entirely offline.
What to take from the run:
url.openConnection()returned aURLConnectionwithout connecting; the network round trip happened only whengetInputStream()was called. That laziness is why timeouts and request properties must be set first — once you read the body, the connection is already established and those settings are locked in.- The header getters and the body stream are two separate channels.
getContentType()andgetContentLength()read response metadata, whilegetInputStream()reads the payload. The server setContent-Typeexplicitly, and the connection surfaced it both through the typed getter and the genericgetHeaderField("Content-Type"). getContentLength()returned the real byte count because the server sent aContent-Lengthheader. When a server omits it (chunked responses), this returns-1— so code that pre-sizes a buffer from it must handle the-1case.- The body was read through try-with-resources, guaranteeing the socket is freed even on an exception. Leaking connection streams exhausts the connection pool and eventually the OS file-descriptor limit — closing is not optional in networking code.
URLConnectionis deliberately protocol-neutral: nothing here mentioned HTTP status codes or request methods. Reading the status, choosing GET vs POST, and accessing the error stream require casting toHttpURLConnection, which the next chapter does.
Practice
A download routine calls 'url.openConnection()' and then immediately starts a 30-second timer before calling 'getInputStream()', expecting the connection to already be open. It also never sets any timeout. Which statement is correct?