2009年7月6日月曜日

Web ページの Content-Type を取得

Web ページの
Content-Type の値を取得してみました。
Content-Type : meta タグの Content-Type 属性で指定する値には、
shift_jis や utf-8 などがあります。

方法は

URL url = new URL("http://~~~~");
String cs = url.openConnection().getContentType();
cs = cs.substring(cs.lastIndexOf("=") + 1);

あるいは

BufferedReader br = new BufferedReader(
                            new InputStreamReader(url.openStream()));
                    String str;
                    while ((str = br.readLine()) != null) {
                        if (str.contains("charset=")) {
                            System.out.println(
                                    str.substring(str.indexOf("charset=") + 8, str.indexOf('"', str.indexOf("charset=") + 8)));
                            break;
                        }    
                    }