Java Get Data From URL
We can access data from a specific URL using a Java program. Java provides URL and URLConnection classes to communicate with the URL over a network. These classes have several useful methods to deal with HTTP URLs.
In this section, we will discuss how to access data from a specific URL using a Java program.
Let's discuss URL and URLConnection classes:
The URL class represents a URL (Uniform Resource Locator), a pointer to web content on the WWW (World Wide Web). Web content can be an ordinary file or directory, query to database, reference to an object, etc.
An example of the URL as follows:
The URL class displays the following information of the URL:
Protocol: A protocol defines the set of rules for communication. In the above URL, the https is a protocol.
Server name or IP Address: Server name or domain name or IP address is the particular address of a Host. In the above example, www.javatpoint.com is the server name.
Port Number: The port number is an optional attribute.
File Name or directory name: The filename is the name of the particular file of your project. In the above example, java-tutorial is the file name.
Consider the below example of Java URL class:
Protocol: https Host Name: www.javatpoint.com Port Number: -1 File Name: /java-tutorial
Read more about the Java URL class.
The URLConnection class specifies a between the URL and our application. This class has methods to read and write data to the specified resource referred by the URL.
The openConnection() method is used to get the object of URLConnection class. It's syntax is as follows:
Read more about the Java URLConnection class.
Let's understand how to get data from URL.
How to Access Data From a URL Using Java
We have discussed the URL and URLConnection Class; now, it is easy to understand how to get data from a given URL. Here, we will access the data using these classes. We will use the combination of InputStreamReader and BufferedReader to read the data from a specified URL. We should follow the below steps to create a Java program for this process:
Let's implement the above steps using Java code:
Consider the below example:
As we can see from the above output, the data is accessed from the url https://www.javatpoint.com/java-tutorial.
Next TopicNo Main Manifest Attribute