Home Java Java-tips Io 20internet Read page from Web server

Ask Questions?

View Latest Questions

Advertisement


 
 

Read page from Web server
Posted on: July 26, 2006 at 12:00 AM
Another way to read from a server

Java Notes

Read page from Web server

The Java io package provides classes and interface for accessing the web pages. You can even access the website pages and download the data.

In this tutorial we are downloading the data from http://www.yahoo.com using our java program and then saving on to our hard disk in a file.

So, with the hop of java program you can download the HTML pages from website and save on disk.

In this example code we have used following classes of java.net package:

a) URL class is used to access the www resource.

b) The we have used the BufferReader class to read the data in buffer

c) Finally retrieved the data in String class and printed on console.

Following is the complete example code in Java which reads the data from website and prints on the console.

/* This program was taken from the Java Tutorial 
   http://java.sun.com/docs/books/tutorial/networking/urls/readingURL.html 
   Modified by Fred Swartz to use the Java 1.1 "Reader" classes.  24 Nov 1997 
*/ 

import java.net.*; 
import java.io.*; 

class ReadURL { 
    public static void main(String[] args) { 
        try { 
            URL yahoo = new URL("http://www.yahoo.com/"); 
            BufferedReader in = new BufferedReader( 
                new InputStreamReader(yahoo.openStream())); 
            String inputLine; 
    
            while ((inputLine = in.readLine()) != null) { 
                // Process each line.
                System.out.println(inputLine); 
            } 
            in.close(); 
    
        } catch (MalformedURLException me) { 
            System.out.println(me); 
    
        } catch (IOException ioe) { 
            System.out.println(ioe); 
        } 
    }//end main 
}//end class ReadURL

Another way to read from a server

It's possible to have more control over the connection by using the URLConnection, or HttpURLConnection classes. For example, using a URLConnection object is very similar to the above example.
  URL yahoo = new URL("http://www.yahoo.com/"); 
  URLConnection yahooConnection = yahoo.openConnection(); 
  BufferedReader in = new BufferedReader( 
             new InputStreamReader(yahooConnection.getInputStream())); 

Lower-level network I/O

Java network I/O is at the level to UPD, TCP, and higher-level protocols (HTTP, SMTP, ...). It is not possible to do network I/O at the very low levels (eg, ICMP), but this is not a problem for any normal programs. However, there are a few programs (like ping and traceroute) that you can not write in Java.
Copyleft 2003 Fred Swartz MIT License, Last update: 2003-05-30
Advertisement


DMCA.com