質問

からコードを入手しました java httpurl接続がhtmlを切断します Java で Web サイトから HTML をフェッチするコードとほぼ同じです。1 つの特定の Web サイトを除いて、このコードを動作させることができません。

この Web サイトから HTML を取得しようとしています。

http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289

しかし、私はジャンクキャラクターを受け取り続けます。次のような他のウェブサイトでも非常にうまく機能しますが、 http://www.google.com.

そして、これは私が使用しているコードです:

public static String PrintHTML(){
    URL url = null;
    try {
        url = new URL("http://www.geni.com/genealogy/people/William-Jefferson-Blythe-Clinton/6000000001961474289");
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    HttpURLConnection connection = null;
    try {
        connection = (HttpURLConnection) url.openConnection();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2.6) Gecko/20100625 Firefox/3.6.6");
    try {
        System.out.println(connection.getResponseCode());
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String line;
    StringBuilder builder = new StringBuilder();
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    try {
        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n"); 
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String html = builder.toString();
    System.out.println("HTML " + html);
    return html;
}

なぜ上記の URL で機能しないのかわかりません。

助けていただければ幸いです。

役に立ちましたか?

解決

そのサイトは、クライアントの機能に関係なく、応答を誤って gzip 圧縮しています。通常、サーバーは、クライアントが応答をサポートするときは常に応答を gzip 圧縮する必要があります ( Accept-Encoding: gzip)。次を使用して解凍する必要があります GZIPInputStream.

reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream()), "UTF-8"));

正しい文字セットも追加したことに注意してください。 InputStreamReader コンストラクタ。通常は、 Content-Type 応答のヘッダー。

その他のヒントについては、以下も参照してください URLConnection を使用して HTTP リクエストを起動して処理するにはどうすればよいですか? 結局のところ、HTML から情報を解析/抽出したいだけの場合は、次のコマンドを使用することを強くお勧めします。 HTMLパーサー 代わりに Jsoup のように。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top