0

Apache HttpClient 4 を使用して Web ページから「タイトル」を取得しようとしています。

編集:私の最初のアプローチは、(HttpHead を使用して) ヘッダーから取得しようとすることでした。それが不可能な場合、@Todd が言うように、どうすれば応答の本文から取得できますか?

編集2:

<head>
[...]
<title>This is what I need to get!</title>
[...]
</head>
4

2 に答える 2

3

コメントありがとうございます。jsoup を使用すると、解決策は非常に簡単でした。

Document doc = Jsoup.connect("http://example.com/").get();
String title = doc.title();

本当にHttpClientを使用して接続する必要があることを考えると、これが私が持っているものです:

org.jsoup.nodes.Document doc = null;
String title = "";

System.out.println("Getting content... ");

CloseableHttpClient httpclient = HttpClients.createDefault();
HttpHost target = new HttpHost(host);
HttpGet httpget = new HttpGet(path);
CloseableHttpResponse response = httpclient.execute(target, httpget);

System.out.println("Parsing content... ");

try {
    String line = null;
    StringBuffer tmp = new StringBuffer();
    BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    while ((line = in.readLine()) != null) {                    
        String decoded = new String(line.getBytes(), "UTF-8");
        tmp.append(" ").append(decoded);
    }

    doc = Jsoup.parse(String.valueOf(tmp)); 

    title = doc.title();
    System.out.println("Title=" + title); //<== ^_^

    //[...]

} finally {
    response.close();
}

System.out.println("Done.");
于 2015-01-23T15:19:28.940 に答える