Backend Development 5 min read

Understanding Java URL and URLConnection

Java’s URL class lets you represent and fetch resources identified by a URL, while URLConnection (and its HttpURLConnection subclass) provides detailed control over HTTP requests such as setting methods, headers, and handling input/output streams, with custom handlers enabling protocol‑specific behavior.

Java Tech Enthusiast
Java Tech Enthusiast
Java Tech Enthusiast
Understanding Java URL and URLConnection

Java's URL class represents a resource identified by a uniform resource locator, e.g., http://baidu.com. It can be used to retrieve the content of a web page.

Example code shows how to create a URL object from the first command‑line argument, open an input stream, and print the page content.

import java.net.*;
import java.io.*;
public class GetINt {
    public static void main(String[] args) throws Exception {
        URL url = new URL(args[0]);
        InputStream html = url.openStream();
        int c;
        do {
            c = html.read();
            if (c != -1) {
                System.out.print((char) c);
            }
        } while (c != -1);
    }
}

For more control over HTTP transactions, URL.openConnection() returns a URLConnection object. When the protocol is HTTP, the returned object is an instance of HttpURLConnection, which allows setting request method, headers, and handling input/output streams.

import java.net.*;
import java.io.*;
public class Handin {
    public static void main(String[] args) throws Exception {
        URL url = new URL("http://example.com");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setDoInput(true);
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        con.setRequestProperty("Content-type", "application/X-WWW-form-urlencoded");
        con.connect();
        PrintWriter pri = new PrintWriter(new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
        pri.print("data=" + URLEncoder.encode(args[0], "UTF-8"));
        pri.flush();
        System.out.println(con.getResponseMessage());
        InputStream in = con.getInputStream();
        int c;
        while ((c = in.read()) != -1) {
            System.out.print((char) c);
        }
    }
}

The URL and URLConnection classes delegate the actual work to URLStreamHandler and URLConnection subclasses. A URLStreamHandlerFactory creates protocol‑specific handlers, which in turn produce appropriate URLConnection objects.

import java.net.*;
import java.io.*;
public class TimeURLConnection extends URLConnection {
    private Socket con;
    public static final int DEFAULT_PORT = 13;
    public void connect() throws IOException {
        if (!connected) {
            int port = url.getPort();
            if (port < 0) port = DEFAULT_PORT;
            con = new Socket(url.getHost(), port);
            connected = true;
        }
    }
    public InputStream getInputStream() throws IOException {
        connect();
        return con.getInputStream();
    }
}

In summary, the URL API provides a simple way to access web resources, while URLConnection and its subclasses give fine‑grained control over HTTP communication.

JavaHTTPCode ExamplenetworkingURLURLConnection
Java Tech Enthusiast
Written by

Java Tech Enthusiast

Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.