wgetやcurlコマンドのようなURLを指定して取得したHTMLコンテンツを画面に表示するサンプルソースです。
以下にサンプルソースおよびコンパイルと実行結果を記します。
本サンプルソースは引数としてURLを入力してください。
HttpGet.java LF
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.URL;
public class HttpGet {
private String url;
private void usage(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java HttpGet <URL>");
System.exit(1);
}
}
HttpGet(String[] args) {
usage(args);
this.url = args[0];
}
public void getContent() {
try {
URL url = new URL(this.url);
Object o = url.getContent();
if (o instanceof InputStream) {
InputStreamReader isr = new InputStreamReader((InputStream)o);
BufferedReader br = new BufferedReader(isr);
String l;
while((l = br.readLine()) != null) {
System.out.println(l);
}
br.close();
isr.close();
} else {
System.out.println("This content is not text! : " + o.toString());
}
} catch (IOException e) {
System.err.println("Network or HTTP error");
System.err.println(e);
System.exit(2);
}
}
public static void main(String[] args) {
HttpGet me = new HttpGet(args);
me.getContent();
}
}
コンパイルして実行します。
$ javac HttpGet.java
$ java HttpGet Usage: java HttpGet <URL>
$ java HttpGet http://java.just4fun.biz <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="ja"> <head> <meta http-equiv="content-type" content="application/xhtml+xml; charset=UTF-8" /> <meta http-equiv="content-style-type" content="text/css" /> <title>FrontPage - Javaコードを書いてみる</title> 省略
$ java HttpGet http://java.just4fun.biz/image/logo.png This content is not text! : sun.awt.image.URLImageSource@647e05
$ java HttpGet http://non.just4fun.biz Network or HTTP error java.net.UnknownHostException: non.just4fun.biz
以上、HTTP GETメソッドのサンプルソースおよび実行例でした。