Specialized Networking APIs for Java

 < Day Day Up > 



Java includes a number of specialized APIs for specialized networking. These include HTTP, URL processing, RMI (remote method invocation), and others. In this section, we look at examples of the HTTP and URL classes.

Java URL Class for HTTP

Java provides a high-level mechanism for dealing with URLs, or Uniform Resource Locators. The URL specifies not only an address, but also a protocol for which the address should be accessed. In Listing 10.1, we use the URL class to connect to a host and with the specification of the HTTP protocol, read the default (index) file, and display it. The entire Java application is shown for completeness.

Listing 10.1 Sample URL example (host.java).

start example
import java.net.*; import java.io.*; public class host {   public static void main( String[] args ) {     URL theUrl;     String line;     try {       theUrl = new URL( "http://www.microsoft.com" );       try {         BufferedReader input =           new BufferedReader(             new InputStreamReader( theUrl.openStream() ));         try {           while ((line = input.readLine()) != null ) {             System.out.println( line );           }         } catch ( Exception e ) { System.out.println( e ); }       } catch ( Exception e ) { System.out.println( e ); }     } catch( MalformedURLException e ) { System.out.println( e ); }   } }
end example

From the example, we create a new URL object, and specify our URL as the Microsoft Web site. Note that the address is in URL format; it contains a protocol specification (“http://”) and an address (“www.microsoft.com”). We then create a BufferedReader stream over our URL object. First, we open the URL using the openStream method, which returns an InputStream object. This is passed anonymously into the InputStreamReader class, which is used by the BufferedReader class to create a BufferedReader object. We can now perform a readLine method on our new BufferedReader object to extract the response to our request (which in the openStream call was an HTTP ‘Get’ request). For each line that is received, we emit it to standard-out.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net