5.2 URLとインターネット上の資源へのアクセス
2.java.net.URLの実装例
URL指定の資源をGETする方法:URLクラスのgetContentメソッドを用いてクラスObjectへ接続する。
なぜ、Objectクラスなのか? → URLが表す資源の実体はさまざまなタイプのデータである可能性があるから。(実際、getContent()の返すオブジェクトは、一般には Objectクラス)
URL資源のデータ形式がテキストファイル(text/html)の場合の処理は非常に簡単である。
この場合、getContent()の返すオブジェクトは InputStream のサブクラス(instanceof ...)になるはず。
以下の例は、URLによって接続された入力ストリームから、行単位でデータを読み込み、標準出力に表示する。
サンプルプログラム URLTextContent.java:
import java.io.*; import java.net.*; /** URLオブジェクトストリームからテキストデータを読込むクラス */ public class URLTextContent { public static void main( String argv[] ) { try { URL url = new URL( argv[0] ); Object content = url.getContent(); if( content instanceof InputStream ) { BufferedReader reader = new BufferedReader( new InputStreamReader( (InputStream)content ) ); String line; while( ( line = reader.readLine() ) != null ) { System.out.println( line ); } reader.close(); } else { System.out.println( "This content is " + content.toString() ); } } catch( ArrayIndexOutOfBoundsException e ){ System.err.println( "Usage: java URLTextContent URL" ); System.exit(-1); } catch( IOException e ){ System.err.println( "Network error!" ); System.exit(-1); } } }【実行例】
URL引数がない場合:
java -classpath . URLTextContent
Usage: java URLTextContent URLHTMLデータをGETできる場合:
java -classpath . URLTextContent http://cai.cs.shinshu-u.ac.jp/index.html
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title></title>
</head>
<body
bgcolor="#ffffff"
text="#000000"
link="#0000ff"
vlink="#000080"
alink="#ff0000"
>
<p>
<a href="sugsi/"> cai.cs.shinshu-u.ac.jp</a>
</p>
</div>
</body>
</html>存在しないURLを指定:
java -classpath . URLTextContent http://foo.bar.com/index.html
Network error!GIF画像ファイルを指定:
java -classpath . URLTextContent http://cai.cs.shinshu-u.ac.jp/sugsi/picture/logo1.gif
This content is sun.awt.image.URLImageSource@1754ad2
2003年10月22日 4:17 更新