Java Reference
In-Depth Information
URL u = new URL ( "http://mesola.obspm.fr/" );
Object o = u . getContent ();
// cast the Object to the appropriate type
// work with the Object...
getContent() operates by looking at the Content-type field in the header of the data
it gets from the server. If the server does not use MIME headers or sends an unfamiliar
Content-type , getContent() returns some sort of InputStream with which the data
can be read. An IOException is thrown if the object can't be retrieved. Example 5-3
demonstrates this.
Example 5-3. Download an object
import java.io.* ;
import java.net.* ;
public class ContentGetter {
public static void main ( String [] args ) {
if ( args . length > 0 ) {
// Open the URL for reading
try {
URL u = new URL ( args [ 0 ]);
Object o = u . getContent ();
System . out . println ( "I got a " + o . getClass (). getName ());
} catch ( MalformedURLException ex ) {
System . err . println ( args [ 0 ] + " is not a parseable URL" );
} catch ( IOException ex ) {
System . err . println ( ex );
}
}
}
}
Here's the result of trying to get the content of http://www.oreilly.com :
% java ContentGetter http: //www.oreilly.com/ I got a
sun . net . www . protocol . http . HttpURLConnection $HttpInputStream </ programlisting >
The exact class may vary from one version of Java to the next (in earlier versions, it's
been java.io.PushbackInputStream or sun.net.www.http.KeepAliveStream ) but it
should be some form of InputStream .
Here's what you get when you try to load a header image from that page:
% java ContentGetter http: //www.oreilly.com/graphics_new/animation.gif
I got a sun . awt . image . URLImageSource </ programlisting >
Here's what happens when you try to load a Java applet using getContent() :
Search WWH ::




Custom Search