Apache Commons HttpClient
サイトをクロールするときに、nekohtmlを使ってたのですが、どうも文字化けするサイトがありました。
nekohtmlでは、HTTPヘッダのContentTypeはきちんと読んでくれるし、そうじゃなくてもMETAタグに書かれているContentTypeも解析してくれてるっぽかったんですが、どうもHTTPヘッダにContentTypeが指定されていなくて、しかもMETAタグ以前にマルチバイトがあるとそのマルチバイトが解析できないようです。
例えばMETAタグ以前にTITLEタグがある場合など。
せっかくなので、他ないか探してみるとApache CommonsにHttpClientというものがあったので、使ってみました。
public static void main(String[] args) throws Exception{
BufferedReader br = null;
HttpClient client = new HttpClient();
GetMethod method = new GetMethod(args[0]);
try {
client.executeMethod(method);
br = new BufferedReader(new InputStreamReader(
method.getResponseBodyAsStream(), method.getResponseCharSet()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = br.readLine()) !=null) {
sb.append(line);
}
System.out.println("encoding = " + method.getResponseCharSet());
System.out.println(sb.toString());
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if(br!=null){
br.close();
br = null;
}
method.releaseConnection();
}}
こんな感じです。
nekohtmlだとNGだったサイトもこれできちんとエンコードしてくれてました。
クロールはこっちを使って、HTMLのパースにnekohtmlを使用することにします。
Posted in Java |
