Instructional Objectives
After participating in this practicum, students are expected to be able to:
- Understanding URLs
- Create a program to implement URL Class.
1. Class URL Class
A URL is the simplest way for a Java program to find and retrieve data from a network. You don't have to worry about the details of the protocol used, the format of the data retrieved, or how to communicate with the server, you just tell it the URL and it gets the data for you.
The java.net.URL class is an abstraction of the Uniform Resource Locator (URL) such as http://www.hamsterdance.com/ or ftp://ftp.redhat.com/pub/. The following program listing is an example of using the URL class, including checking a URL and various ways to write it using the URL class.
The URL consists of five parts, namely Scheme or known as protocol, authority, path, identifier fragment, also known as part or ref and query string. Examples are as follows:
http://java.sun.com:80/docs/books/tutorial/index.html#DOWNLOADING
Examples of its application are as follows:
import java.net.*;
public class urltest1 {
public static void main (String args[]) {
URL webURL, ftpURL;
try {
webURL = new URL("http://www.macfaq.com/vendor.html");
System.out.println(webURL);
ftpURL = new URL("ftp://ftp1.macfaq.com/pub/");
System.out.println(ftpURL);
} catch (MalformedURLException e) {
System.err.println("URL Salah");
}
}
}
2. Connection URL
URLConnection is an abstract class that represents an active connection to a resource specified by a URL. The URLConnection class has two different but related purposes. First, it provides more control over interactions with a server (especially an HTTP server) than the URL class. With a URLConnection, you can inspect the headers sent by the server and the corresponding responses. You can set the header fields used in client requests. You can use a URLConnection to download binary files. Finally, a URLConnection allows you to send data back to a web server with POST or GET and use other HTTP request methods.
To create a program that uses the URLConnection class, the following basic steps are required:
- Create a URL object.
- Call the openConnection() method to retrieve a URLConnection object from a URL.
- Configure the URLConnection.
- Read the header fields.
- Get input stream and read data.
- Get output stream and write data.
- Closing the connection.
The example program will read data from the URL www.unisbank.ac.id. The result of the program is the HTML codes that make up the web.
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception{
URL alamat = new URL("http://www.unisbank.ac.id");
URLConnection yc = alamat.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}