The URL and URLConnection classes are part of Java's standard library and are used for working with URLs (Uniform Resource Locators) and accessing resources on the Internet.
URL Class: The URL class is used to represent a URL. It has several methods for parsing a URL string and obtaining information about the URL, such as the protocol, host, port, file path, etc. The URL class can be used to connect to a URL and retrieve the contents of a web page, for example.
Example:
javaimport java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class URLDemo {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
URLConnection Class: The URLConnection class is a subclass of URL and provides more advanced functionality for connecting to a URL and sending and receiving data. It is used to establish a connection to a URL and perform I/O operations, such as sending and retrieving data.
Example:
javaimport java.net.URL;
import java.net.URLConnection;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
public class URLConnectionDemo {
public static void main(String[] args) throws IOException {
URL url = new URL("https://www.example.com");
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
In both examples, the URL and URLConnection classes are used to retrieve the contents of a web page from a URL and print it to the console. The URL class is simpler and provides a convenient way to connect to a URL, while the URLConnection class provides more advanced functionality for working with URLs and performing I/O operations.