Skip to content
ELECTRONICS ENGINEERINGelectronics-engineering.com
Java

Reading from a URL with Java

Common JAVA applications take information from the Internet in order to manipulate it. To do this you need to read the content of any WEB site properly. This is a Web client…

https://www.electronics-engineering.com/en/reading-from-a-url-with-java/

Was this page useful? Rate it:
average 5.0 from 1 rating

Common JAVA applications take information from the Internet in order to manipulate it. To do this you need to read the content of any WEB site properly.

This is a Web client (that is, http) and the scheme to use is the following:

  • Create a Url object with the desired address.
  • Create a URLConnection object by opening a connection to the URL
  • Create a chain of input streams and attach it to the connection.
  • Read the Web document from this chain.
  • Close the chain.
import java.net.*;
import java.io.*; 
class FetchURL { 
   public static void main (String[] args) { 
       try { 
         URL cernHome = new URL ('https://www.electronics-engineering.com'); 
         URLConnection cernHomeConnection = cernHome.openConnection(); 
         BufferedReader in = new BufferedReader( new InputStreamReader (cernHomeConnection.getInputStream())); 
         String inputLine; 
         while ( (inputLine=in.readLine())!=null) { 
            System.out.println(inputLine); 
         } 
         in.close(); 
      } catch (MalformedURLException e) { 
         System.out.println('Malformed URL Exception '+e); 
      } catch (IOException e ) { 
         System.out.println('IO Exception '+e); 
      } 
   } 
}

The tool’s output is printed on screen. Simple changes to this script send the output to an ascii file or to a string variable.

Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
1
0
Would love your thoughts, please comment.x
()
x