Networking

networking4UrlAndConnection

Path
pkg10networking/networking4UrlAndConnection.java
Package
pkg10networking
Study order
4
Run
Single-file source launch
Command
java pkg10networking/networking4UrlAndConnection.java
Dependencies
com.sun.net.httpserver.HttpServer

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg10networking/networking4UrlAndConnection.java
1package pkg10networking;2 3import com.sun.net.httpserver.HttpServer;4import java.io.BufferedReader;5import java.io.InputStreamReader;6import java.net.InetSocketAddress;7import java.net.URI;8import java.net.URL;9import java.net.URLConnection;10import java.nio.charset.StandardCharsets;11 12/*13 * networking4UrlAndConnection.java14 * --------------------------------15 * The classic URL / URLConnection API for fetching resources over HTTP.16 *17 * DEFINITION:18 *   A URL identifies a resource (scheme://host:port/path?query). URLConnection19 *   opens a stream to it. This is the older API; prefer HttpClient (networking5)20 *   for new code. We fetch from a tiny in-process server so it runs offline.21 *22 * KEY POINTS:23 *   - Parse a URL to inspect protocol, host, port, path, query.24 *   - openConnection() + getInputStream() reads the response body.25 *   - Build URLs via URI.create(...).toURL() (the URL(String) ctor is deprecated).26 *   - Set headers/timeouts on the URLConnection before connecting.27 */28public class networking4UrlAndConnection {29 30    public static void main(String[] args) throws Exception {31        // Start a local server that returns a fixed body32        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);33        server.createContext("/hello", ex -> {34            byte[] body = "Hello from URLConnection demo".getBytes(StandardCharsets.UTF_8);35            ex.getResponseHeaders().add("Content-Type", "text/plain");36            ex.sendResponseHeaders(200, body.length);37            ex.getResponseBody().write(body);38            ex.close();39        });40        server.start();41        int port = server.getAddress().getPort();42 43        // Parse a URL and inspect its parts44        URL url = URI.create("http://127.0.0.1:" + port + "/hello?lang=en").toURL();45        System.out.println("protocol = " + url.getProtocol());46        System.out.println("host     = " + url.getHost());47        System.out.println("port     = " + url.getPort());48        System.out.println("path     = " + url.getPath());49        System.out.println("query    = " + url.getQuery());50 51        // Open a connection, set a header/timeout, and read the body52        URLConnection conn = url.openConnection();53        conn.setRequestProperty("Accept", "text/plain");54        conn.setConnectTimeout(2000);55        System.out.println("\nContent-Type: " + conn.getContentType());56        try (BufferedReader in = new BufferedReader(57                new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8))) {58            System.out.println("Body        : " + in.readLine());59        }60 61        server.stop(0);62    }63}