URLConnection: reading from a URL

java.net.URLConnection  is a class that links the application to the URL. To get an HTTP response, you first need to create a connection with the two-step url:
  • openConnection: this method creates the object connection which configures the connection parameters and receive parameters.
  • URLConnection.connect: Creates interaction with the resource by initiating the communication between the Java program and the url.
The following code creates a connection to the http:// site www.codeurjava.com.

URL url=null; 
try {
url = new URL("http://www.codeurjava.com");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
URLConnection con = url.openConnection();
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The URLConnection object is created each time the connection is made with openConnection(). Now that the connection is successfully established, you can use URLConnection to read and write to the url with the InputStream and outputStream.

Read from URLConnection

This program retrieves the inputStream object, the connection is opened with the getInputStream() method, then it creates a BufferedReader on that InputStream and reads the contents. line by line with the readline() method that we need to load it in a variable of type String.

import java.io.BufferedReader; 
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class URLConnectionExample:{

public static void main(String[] args) {
String host = "http://www.codeurjava.com/";
URL aURL = null;
String codeHTML = "";
try {
aURL = new URL(host);
//open connection
URLConnection con = aURL.openConnection();
//maximum time allotted to connect
con.setConnectTimeout(60000);
//maximum time allotted to read
con.setReadTimeout(60000);
//read stream with UTF-8 character encoding
BufferedReader in = new BufferedReader(
new InputStreamReader(
con.getInputStream(),"UTF-8"));
String inputline;
while((inputline = in.readLine())!=null){
//concatenation+newline with \n
HTML code += inputline+"\n";
}
//the playback stream must be closed
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(codeHTML);
}
}
Result

 

< head>
< title> JAVA Development Tutorials and Examples
.
.
.



This code retrieves the HTML code in Java. If the program displays an error message, then the program has not been able to find the server or the url is not reachable. In our program, we have programmed the maximum time allowed for connection and playback to be 6 seconds. After this time, the program stops.

References
Oracle: Class URL: openConnection
upenn: Class java.net.URLConnection
StackOverFlow:  Using java.net.URLConnection to fire and handle HTTP requests?