Welcome!

Java Authors: Torben Andersen, Sergio Varga, Liz McMillan, Elizabeth White, Patrick Carey

Related Topics: Java

Java: Article

Reading Data from the Internet

Lesson 6, Java Basics

To read local file streams, a program has to specify the file's location, i.e. "c:\practice\training.html". The same procedure is valid for reading of the remote files: just open the stream over the network. Java has a class URL that will help you to connect to a remote computer on the Internet.

At first, create an instance of the class URL:

try{
  URL xyz = new URL("http://www.xyz.com:80/training.html");
}
catch(MalformedURLException e){
      e.printStackTrace();
}

The MalformedURLException could be thrown if a non-valid URL has been used, for example missed protocol if you forgot to start URL with http://, extra spaces, etc. The MalformedURLException does not indicate that the remote machine has problems - just check the spelling of the URL.

Creation of the URL object does not establish the connection with the remote machine: you'll still need to open a stream to read it. Usually you have to perform the following steps to read a file from the Internet:

Step 1. Create and instance of the class URL

Step 2. Create an instance of the class URLConnection and open a connection using the URL instance from step 1.

Step 3. Get a reference to an input stream of this object by calling the method URLConnection.getInputStream()

Step 4. Read the data from the stream (use the buffered reader to speed up the process).

Since the streams from the package java.io are being used here for the read/write operations, you'll have to handle I/O exceptions.

The server you are trying to connect to has to be up and running and, in case of using http protocol, the special software (Web Server) has to be "listening to" the port that you specified in the URL instance. By default, Web servers are listening to the port number 80.

The program below reads and prints on the system console the content of the file index.html from yahoo.com. Obviously, to test this program your computer has to be connected to the Internet.

import java.net.*;
import java.io.*;
public class WebSiteReader {
  public static void main(String args[]){
       String nextLine;
       URL url = null;
       URLConnection urlConn = null;
       InputStreamReader  inStream = null;
       BufferedReader buff = null;
       try{
          // Create the URL obect that points
          // at the default file index.html
          url  = new URL("http://www.yahoo.com" );
          urlConn = url.openConnection();
         inStream = new InputStreamReader( 
                           urlConn.getInputStream());
           buff= new BufferedReader(inStream);
        
       // Read and print the lines from index.html
        while (true){
            nextLine =buff.readLine();  
            if (nextLine !=null){
                System.out.println(nextLine); 
            }
            else{
               break;
            } 
        }
     } catch(MalformedURLException e){
       System.out.println("Please check the URL:" + 
                                           e.toString() );
     } catch(IOException  e1){
      System.out.println("Can't read  from the Internet: "+ 
                                          e1.toString() ); 
  }
 }
}

The class WebSiteReader explicitly creates the URLConnection object. Strictly speaking we could get away just with the class URL:

URL url = new URL("http://www.yahoo.com");
InputStream in = url.getInputStream();
Buff= new BufferedReader(new InputStreamReader(in));

The reason why you may consider using the URLConnection class is that it could give you some additional control over the I/O process. For example, by calling its method setDoInput(true) you could allow (or disallow) downloads.

Connecting Through HTTP Proxy Servers

Most of the companies use firewalls for security reasons and their employees reach the Internet through the HTTP proxy server. Check the settings of your Internet browser to find out the host name and port number of the proxy server. If you are using Microsoft Internet Explorer check the menu Internet Options | Connections | LAN Setting. Netscape Navigator has proxy settings under Preferences | Advanced | Proxies.

While Java Applets know parameters of the proxy servers because they live inside the browser that has the proper settings, Java applications should set the parameters of the proxy server, for example:

   System.setProperty("http.proxyHost","xyz.com");
   System.setProperty("http.proxyPort", 8080);

If you do not want to hardcode these value, pass them to the program from the command line:

c:\practice>java -Dhttp.proxyHost=xyz.com  -Dhttp.proxyPort=8080  WebSiteReader

If you run this program without specifying the proxy settings, you'll get the UnknownHostException.

How to Download Files From the Internet

By using the class URL with input streams, we should be able to download practically any file (images, music, binary files) from the unsecured Internet site. The trick is in proper opening of the file stream. Let‚s write the class FileDownload that takes a URL and the file name as a command line arguments and copies remote file on your local disk.

import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.DataInputStream;
import java.net.URL;
import java.net.URLConnection;

class FileDownloader{

  public static void main(String args[]){
    if (args.length!=2){
      System.out.println(
        "Proper Usage: java FileDownloader RemoteFileURL LocalFileName");
      System.exit(0);
    }

  DataInputStream in=null;
  DataOutputStream out=null;
  FileOutputStream fOut=null;

  try{
    URL remoteFile=new URL(args[0]);
    URLConnection fileStream=remoteFile.openConnection();

    // Open the input streams for the remote file 
    fOut=new FileOutputStream(args[1]);

    // Open the output streams for saving this file on disk
    out=new DataOutputStream(fOut);

    in=new DataInputStream(fileStream.getInputStream());

    // Read the remote on save save the file
    int data;
    while((data=in.read())!=-1){
         fOut.write(data);
    }  
    System.out.println("Download of " + args[0] + " is complete." );   
  } catch (Exception e){
     e.printStackTrace();
  } finally {
     try{
       in.close();
       fOut.flush(); 
       fOut.close();      
     } catch(Exception e){e.printStackTrace();}
     
    }
 }
}

To download the Yahoo's main page into c:\temp directory start this program as follows:

java FileDownloader http://www.yahoo.com/index.html c:\\temp\\yahoo.html

The Stock Quote Program

In this section we'll write the program that can read stock market quotes from the Internet. There are many Internet sites providing stock market quotes, and 20 minutes delayed quotes are free. Wall Street companies subscribe for the real-time market data feed. One of the popular Internet sites is Yahoo and the URL for getting stock prices is http://finance.yahoo.com Point your Web browser to this site and get the price quote of any stock symbol. Note the URL of the resulting Web page in your browser. For example, if you've selected the symbol IBM, the URL would look like this:

 http://finance.yahoo.com/q?s=IBM

Right click on this page and select the View Source from the popup menu to see the HTML contents of this page: you'll see lots of HTML tags and the information about the IBM's trading will be buried somewhere deep inside the file:


...
   Last Trade:</TD><TD class=yfnc_tabledata1><BIG><B>95.32</B>
...

The next step is to modify the URL in our class WebSiteReader to print the content of the page about the symbol IBM:

    url  = new URL("http://finance.yahoo.com/q?s=IBM");

You can also store the whole page in a Java String variable instead of printing it. Just change the while loop to look as follows:

        String theWholePage;
        while (txt =buff.readLine() != null ){
             theWholePage=theWholePage + txt;
         }

If you add some smart tokenizing of theWholePage to get rid of all HTML tags and everything but Last Trade value, you can create your own little GUI Stock Quote screen. While this approach is useful to sharpen you tokenizing skills, it may not be the best solution, especially if Yahoo will change the wording of this page. That's why we'll be using another Yahoo's URL that provide stock quotes in a cleaner comma separated values format (CSV).

Here's the URL that should be used for the IBM's symbol:

http://quote.yahoo.com/d/quotes.csv?s=IBM&f=sl1d1t1c1ohgv&e=.csv

This URL would produce a string that looks something like this (the price quotes are not real):

"IBM",95.32,"1/16/2004","5:01pm",+1.30,95.00,95.35,94.71,9305000

The next class StockQuoter prints the price quote for the symbol that is specified as a command line argument.

import java.net.*;
import java.io.*;
import java.util.StringTokenizer;

public class StockQuoter {
       String csvString;
       URL url = null;
       URLConnection urlConn = null;
       InputStreamReader  inStream = null;
       BufferedReader buff = null;

     StockQuoter(String symbol){

       try{
           url  = new              
               URL("http://quote.yahoo.com/d/quotes.csv?s="
                   + symbol + "&f=sl1d1t1c1ohgv&e=.csv" );
           urlConn = url.openConnection();
           inStream = new
               InputStreamReader(urlConn.getInputStream());
           BufferedReader buff= new BufferedReader(inStream);

           // get the quote as a csv string
           csvString =buff.readLine();  

           // parse the csv string
              StringTokenizer tokenizer = new
                          StringTokenizer(csvString, ",");
              String ticker = tokenizer.nextToken();
              String price  = tokenizer.nextToken();
              String tradeDate = tokenizer.nextToken();  
              String tradeTime = tokenizer.nextToken();  

              System.out.println("Symbol: " + ticker + 
                " Price: " + price + " Date: "  + tradeDate 
                + " Time: " + tradeTime);
     } catch(MalformedURLException e){
         System.out.println("Please check the spelling of the URL:" 
         		           + e.toString() );
     } catch(IOException  e1){
      System.out.println("Can't read from the Internet: " + 
                                           e1.toString() ); 
     }
     finally{
         try{
           inStream.close();
           buff.close();   
         }catch(Exception e){
            e.printStackTrace();
         }
     }  
   } 

  public static void main(String args[]){
       if (args.length==0){
          System.out.println(
                     "Sample Usage: java StockQuoter IBM");
          System.exit(0);
       } 
       StockQuoter sq = new StockQuoter(args[0]);
  }

}

To see the latest price of IBM stock start the StockQuoter program as follows:

c:\practice>java StockQuoter IBM

In this lesson I tried to show you that working with the streams over the net may be as simple as dealing with files on your local disk. These days Java runs remote-controlled Mars rovers, and this is not a rocket science anymore - just open a Java stream that points at Mars.

More Stories By Yakov Fain

Yakov Fain is a co-founder of two software companies: Farata Systems and SuranceBay. He authored several technical books and lots of articles on software development. Yakov is Java Champion (https://java-champions.java.net). He leads leads Princeton Java Users Group. Two of Yakov's books will go in print this year: "Enterprise Web Development" (O'Reilly) and "Java For Kids" (No Starch Press).

Comments (19) View Comments

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


Most Recent Comments
Dave Mason 10/18/07 03:00:39 AM EDT

Hello Yakov,
how can I read data in real time from java applet for example:
http://www.saxobank.com/?id=911&Lan=EN&Au=1&Grp=5

nitin 11/27/04 02:34:32 AM EST

hi,
can any one tell me how can i read the parameters from URL that has been passed by someone ie id someone send id=123 then how can i get it,how the whole process work & last but the mostimp i want to do whole thing through core java.
Bye

MIchael Behrens 02/08/04 08:17:43 PM EST

Great Article! Keep''m coming!
There is also a good WebCopy implementation at:
http://www.acme.com/java/software/
It makes all the web references local - It does not work on HTTPS - I wish I had all the know-how & code to make an equivalent HTTPS WebSiteReader, which would be very handing for testing our query pages.
Thanks!

Ferruccio Spagna 01/31/04 10:13:33 AM EST

I am very happy with your code, Yakov.
I tried it and everything works very well.
Thanks Ferruccio

Yakov Fain 01/31/04 08:59:53 AM EST

In this lesson I do this using HTTP GET request by attaching parameters to the URL after a question mark separated with an ampersand.

Fo HTTP POST, after getting the URLConnection stream, do something like this:

urlConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConn.setDoOutput(true);

String myData = "myParam1=" + URLEncoder.encode ("abc") +
"&myParam2=" + URLEncoder.encode ("xyz");

DataOutputStream encodedParams = new DataOutputStream (urlConn.getOutputStream ());

encodedParams.writeBytes (myData);
encodedParams.flush ();
encodedParams.close ();

Ferruccio Spagna 01/31/04 08:29:47 AM EST

Ok. What you say occurs when you have a page with a form. Well known. But my question was: you want to read the stream (see your last article) and perhaps manipulate it. You then use the code:
java.net.URL url = new java.net.URL("http://www.cgi.com");
java.net.URLConnection c = url.openConnection();
java.io.DataInputStream dis = new java.io.DataInputStream(c.getInputStream());
and so on.
How can you give the parameters to the cgi with THESE code lines?

Yakov Fain 01/31/04 08:16:45 AM EST

Well, here''s the sample from my book "The Java Tutorial for the Real World".

1. An HTML form has 2 fields to perform a book search:

Find a book

Enter a word from the book title:

2. The servlet FindBooks runs on the server side, gets the parameters and sends back to the browser a page that reads that this book cost $65:

public class FindBooks extends javax.servlet.http.HttpServlet {

public void doGet(HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
String title;
PrintWriter out = res.getWriter();
title = req.getParameter("booktitle");
res.setContentType("text/html");

out.println("");

out.println("the book "+title+" costs only $65");

out.println("Please enter your credit card number");

out.println("");
}
}

Ferruccio Spagna 01/31/04 07:33:44 AM EST

Thank you for your answer. I have several good Java books, but I didn''t find how I can read a CGI URL stream passing POST parameters in the calling instruction anywhere. Tell me please in a few words the way, if it is possible.

Yakov Fain 01/30/04 07:38:59 PM EST

Ferruccio,

Java Servlets and JavaServer Pages technologies deal with HTTP Post and Get requests, parameters, etc. Wait for my lesson on servlets, or get a good book if you need to know the answer now.

Ferruccio Spagna 01/30/04 06:10:50 PM EST

I add to my above question: how can I pass the parameter values calling the URL?

Ferruccio Spagna 01/30/04 05:59:24 PM EST

What about reading a CGI URL accepting METHOD=POST parameters?

Yakov Fain 01/29/04 11:27:25 PM EST

Dennis,

You can run on the remote machine one of the following: RMI server, SocketServer, a Servlet,FTP server... that has to create an instance of the class java.io.File that points at your directory. The File.list() will return the list of files in this directory as a String array. Now create instances of File for each of the array elements and call File.lastModify() to check the timestamp. After finding the file with the proper date, send its URL (or a stream reference) to the client for reading.

Dennis Christopher 01/29/04 01:44:43 PM EST

I found the article useful, and above average in clarity.

I am wondering if anyone knows how you set up the
connection to download an (entire) directory of files?
and to check the file dates before doing so?

Josh Davis 01/28/04 12:49:02 PM EST

Yakov,

You should mention that HttpURLConnection may ''hang'' when contacting servers that don''t behave correctly. This can cause a lot of problems in a server side application. The solutions are:
1) Use something other than URL/URLConnection/HttpURLConnection.
2) Set the system properties that control the socket timeouts for the Sun HTTP client.

John Pantone 01/26/04 01:55:42 PM EST

Very useful, clear.

Yakov Fain 01/23/04 09:49:54 PM EST

If the proxy requires authentication, set the following properties:

System.setProperty("http.proxyUser", "JLarkin");
System.setProperty("http.proxyPassword", "YourPassword");

You may also try using the class java.net.Authenticator

John Larkin 01/23/04 11:28:08 AM EST

Our proxy server requires a user_id and password.
I am having trouble finding a method to set these.
Any ideas ? Thanks

Selvan Rajan 01/23/04 10:10:41 AM EST

What would be the case to deal with cookies from some of the web sites? Especially it becomes cumbersome, if there is a redirection involved after setting the cookie.
Any ideas?

Debashish 01/23/04 02:07:51 AM EST

In the following para :
Strictly speaking we could get away just with the class URL:
URL url = new URL("http://www.yahoo.com");
InputStream in = url.getInputStream();
Buff= new BufferedReader(new InputStreamReader(in));

I think the second line of code should be :
InputStream in = url.openStream();

@ThingsExpo Stories
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...