Read the URL – Java

This short program demonstrates the URL and URLConnection classes by attempting to open a connection to a URL and read text from it. The url must be specified on the command line. If an error occurs, a message is output. Otherwise, the text from the URL is copied to the screen.

/*******************************************************
*     MYCPLUS Sample Code - https://www.mycplus.com     *
*                                                     *
*   This code is made available as a service to our   *
*      visitors and is provided strictly for the      *
*               purpose of illustration.              *
*                                                     *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/
import java.net.*;
import java.io.*;

public class ReadURL {

   public static void main(String[] args) {
      if (args.length == 0) {
         System.out.println("Please specify a URL on the command line.");
         return;
      }
      try {
         readTextFromURL(args[0]);
      }
      catch (Exception e) {
         System.out.println("\n*** Sorry, an error has occurred ***\n");
         System.out.println(e);
      }
   }

   static void readTextFromURL( String urlString ) throws Exception {
        // This subroutine attempts to copy text from the
        // specified URL onto the screen.  All errors must
        // be handled by the caller of this subroutine.

      /* Open a connection to the URL, and get an input stream
         for reading data from the URL. */
      URL url = new URL(urlString);
      URLConnection connection = url.openConnection();
      InputStream urlData = connection.getInputStream();

      /* Check that the content is some type of text.  Note: If
         getContentType() method were called before getting
         the input stream, it is possible for contentType to be
         null only because no connection can be made.  The
         getInputStream() method will throw an error if no
         connection can be made. */
      String contentType = connection.getContentType();
      if (contentType == null || contentType.startsWith("text") == false)
         throw new Exception("URL does not refer to a text file.");

      /* Copy characters from the input stream to the screen, until
         end-of-file is encountered  (or an error occurs). */
      while (true) {
         int data = urlData.read();
         if (data 
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post