4 3 URL and URLConnection Explained
URL and URLConnection are essential classes in Java for handling network resources and establishing connections to web servers. Understanding these classes is crucial for mastering Java SE and preparing for the Oracle Certified Professional, Java SE (OCP Java SE) exam.
Key Concepts
1. URL (Uniform Resource Locator)
A URL is a reference to a web resource that specifies its location on a network and the mechanism for retrieving it. In Java, the URL
class represents a URL and provides methods to parse and manipulate URLs.
2. URLConnection
URLConnection is an abstract class that represents a connection between the application and a URL. It provides methods to read from and write to the resource referenced by the URL.
Detailed Explanation
1. URL
The URL
class in Java allows you to create and manipulate URLs. It provides methods to access the different parts of a URL, such as the protocol, host, port, and file.
import java.net.URL; public class URLExample { public static void main(String[] args) { try { URL url = new URL("https://www.example.com/path/to/resource?query=param"); System.out.println("Protocol: " + url.getProtocol()); System.out.println("Host: " + url.getHost()); System.out.println("Port: " + url.getPort()); System.out.println("File: " + url.getFile()); System.out.println("Query: " + url.getQuery()); } catch (Exception e) { e.printStackTrace(); } } }
2. URLConnection
The URLConnection
class allows you to establish a connection to a URL and interact with the resource. It provides methods to set request properties, read response headers, and retrieve input and output streams.
import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.InputStreamReader; public class URLConnectionExample { public static void main(String[] args) { try { URL url = new URL("https://www.example.com"); URLConnection connection = url.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (Exception e) { e.printStackTrace(); } } }
Examples and Analogies
URL
Think of a URL as an address on a map. Just as an address specifies the location of a house, a URL specifies the location of a resource on the internet. The URL
class helps you understand and navigate this address.
URLConnection
Think of URLConnection as a communication channel between you and a house (resource). Once you have the address (URL), you can establish a connection (URLConnection) to interact with the house, such as sending a message (request) and receiving a response.