Java URL Class
URL (Uniform Resource Locator) is the abbreviation for Uniform Resource Locator, used to locate resources on the Internet. In Java,java.net.URLthe class provides functionality for handling URLs, allowing developers to create URL objects, parse URL components, and establish network connections.
Basic Structure of URL Class
A standard URL typically consists of the following parts:
protocol://host:port/path?query#fragment
For example:
https://www.example.com:8080/products?id=123#details
Main Components
- Protocol:https
- Host:www.example.com
- Port:8080
- Path:/products
- Query Parameters:id=123
- Fragment:details
Creating URL Objects
Java provides multiple constructor methods to create URL objects:
1. Using a Complete URL String
Example
try {
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https://www.example.com");
} catch (MalformedURLException e) {
e.printStackTrace();
}
2. Specifying Protocol, Host, and File Separately
Example
try {
URL url = new URL("https", "www.example.com", "/index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https", "www.example.com", "/index.html");
} catch (MalformedURLException e) {
e.printStackTrace();
}
3. Specifying Protocol, Host, Port, and File
Example
try {
URL url = new URL("https", "www.example.com", 8080, "/api/data");
} catch (MalformedURLException e) {
e.printStackTrace();
}
URL url = new URL("https", "www.example.com", 8080, "/api/data");
} catch (MalformedURLException e) {
e.printStackTrace();
}
Common Methods of URL Class
Getting URL Component Information
Example
URL url = new URL("https://www.example.com:8080/products?id=123#details");
System.out.println("Protocol: " + url.getProtocol()); // https
System.out.println("Host: " + url.getHost()); // www.example.com
System.out.println("Port: " + url.getPort()); // 8080
System.out.println("Path: " + url.getPath()); // /products
System.out.println("Query: " + url.getQuery()); // id=123
System.out.println("Fragment: " + url.getRef()); // details
System.out.println("Protocol: " + url.getProtocol()); // https
System.out.println("Host: " + url.getHost()); // www.example.com
System.out.println("Port: " + url.getPort()); // 8080
System.out.println("Path: " + url.getPath()); // /products
System.out.println("Query: " + url.getQuery()); // id=123
System.out.println("Fragment: " + url.getRef()); // details
Opening Network Connections
The URL class provides several methods for opening network connections:
- openConnection(): Returns a URLConnection object
- openStream(): Opens an input stream for reading data
Example
// Use openStream() to read web page content
try (InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream in = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
URL Encoding and Decoding
In URLs, certain characters need to be encoded (such as spaces, Chinese characters, etc.). Java provides the URLEncoder and URLDecoder classes to handle encoding and decoding.
URL Encoding Example
Example
String query = "name=Zhang San&age=25";
String encodedQuery = URLEncoder.encode(query, "UTF-8");
System.out.println(encodedQuery); // Output: name%3D%E5%BC%A0%E4%B8%89%26age%3D25
String encodedQuery = URLEncoder.encode(query, "UTF-8");
System.out.println(encodedQuery); // Output: name%3D%E5%BC%A0%E4%B8%89%26age%3D25
URL Decoding Example
Example
String decodedQuery = URLDecoder.decode(encodedQuery, "UTF-8");
System.out.println(decodedQuery); // Output: name=Zhang San&age=25
System.out.println(decodedQuery); // Output: name=Zhang San&age=25
Practical Application Examples
Example 1: Downloading a File
Example
URL fileUrl = new URL("https://example.com/files/sample.pdf");
try (InputStream in = fileUrl.openStream();
FileOutputStream out = new FileOutputStream("sample.pdf")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File download completed");
} catch (IOException e) {
e.printStackTrace();
}
try (InputStream in = fileUrl.openStream();
FileOutputStream out = new FileOutputStream("sample.pdf")) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
System.out.println("File download completed");
} catch (IOException e) {
e.printStackTrace();
}
Example 2: Calling a REST API
Example
URL apiUrl = new URL("https://api.example.com/data?param1=value1");
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(apiUrl.openStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("API Response: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(apiUrl.openStream()))) {
StringBuilder response = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
response.append(line);
}
System.out.println("API Response: " + response.toString());
} catch (IOException e) {
e.printStackTrace();
}
Notes
- Exception Handling: URL constructors may throw MalformedURLException, and network operations may throw IOException
- Security: Avoid constructing URLs from untrusted sources
- Performance: For frequent network requests, consider using a connection pool
- Encoding: Ensure correct handling of URL encoding, especially when non-ASCII characters are included