#author("2017-07-16T22:10:39+09:00","","")
#navi(../)
* JavaでHTTP GETメソッド実装サンプル [#o0d45401]
wgetやcurlコマンドのようなURLを指定して取得したHTMLコンテンツを画面に表示するサンプルソースです。~
以下にサンプルソースおよびコンパイルと実行結果を記します。
#contents
#htmlinsert(java_ads_top.html)
* HTTP GET サンプルソース [#f27dddba]
本サンプルソースは引数としてURLを入力してください。
&ref(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();
}
}
* 実行結果 [#u4e80809]
コンパイルして実行します。
$ 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メソッドのサンプルソースおよび実行例でした。
#htmlinsert(java_ads_btm.html)