~/ learn/ comp-348/ cards/ URLConnection: the lifecycle and reading data
1 of 4

Configure a URLConnection, then read the body once

Configure a URLConnection, then read the body once

Answer

URLConnection conn = new URL(args[0]).openConnection(); conn.setConnectTimeout(10_000); conn.setReadTimeout(10_000); conn.setRequestProperty("User-Agent", "comp348/1.0"); try (InputStream in = new BufferedInputStream(conn.getInputStream())) { in.transferTo(System.out); }

Three setters while the object is still unconnected, then one call that connects and returns the stream. transferTo copies the body straight through; try-with-resources closes the stream, and with it the socket, on every path.

Harold 4e ch7 §Reading Data from a Server; JDK javadoc java.io.InputStream

space flip · ← → navigate · esc to exit
NORMAL ~/memra/library/8155d63e-81a0-4a4d-95a2-1196eac5bd2a/flashcard utf-8 LF