How to get URL content in Java
Reading from a URL is as easy as reading from an input stream. URL is the acronym for Uniform Resource Locator . Java programs that interact with the Internet also may use URLs to find the resources on the Internet they wish to access. Java programs can use a class called URL in the java.net package to represent a URL address . A URL takes the form of a string that describes how to find a resource on the Internet. URLs have two main components: the protocol needed to access the resource and the location of the resource. The easiest way to create a URL object is from a String that represents the human-readable form of the URL address.
URL url = new URL("https://net-informations.com/");
Steps for reading URL Content from webserver:
- Create a URL object from the String representation.
- Create a new BufferedReader, using a new InputStreamReader with the URL input stream.
- Read the text, using readLine() API method of BufferedReader.
import java.net.*;
import java.io.*;
public class TestClass {
public static void main(String[] args) throws Exception {
try{
URL url = new URL("https://net-informations.com/");
BufferedReader reader = new BufferedReader(
new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null)
System.out.println(line);
reader.close();
}catch(Exception ex){
System.out.println(ex);
}
}
}
When you run the program, you should see the HTML commands and textual content from the HTML file located at "https://net-informations.com/" scrolling by in your command window. Or, you might see the following error message:
IOException: java.net.UnknownHostException: www.yahoo.com
Related Topics