【问题标题】:How to get the "Title" from a webpage using HttpClient如何使用 HttpClient 从网页中获取“标题”
【发布时间】:2023-03-03 00:49:02
【问题描述】:

我正在尝试使用 Apache HttpClient 4 从网页中获取“标题”。

编辑:我的第一种方法是尝试从标题中获取它(使用 HttpHead)。如果这是不可能的,我怎样才能从响应的正文中得到它,就像@Todd 所说的那样?

编辑 2:

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

【问题讨论】:

  • 您确定您的目标服务器正在发回“标题”标头吗?
  • 标题不在响应标头中,它是响应正文中返回的 HTML 的一部分(如果有的话)。
  • @MrWiggles 是的。我相当确定。我正在使用 ibm.com 进行测试,它在 部分中有一个 标记。
  • @Todd 我编辑了我的问题...谢谢
  • 检查 jsoup.org 是否有一个不错的基于 Java 的 HTML 解析器/抓取工具

标签: java httpclient http-head


【解决方案1】:

感谢大家的 cmets。使用 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.");

【讨论】:

【解决方案2】:

通过使用此代码片段,您仍然可以通过证明其 URL 来检索网页的&lt;title&gt;

InputStream response = null;
    try {
        String url = "http://example.com/";
        response = new URL(url).openStream();


        Scanner scanner = new Scanner(response);
        String responseBody = scanner.useDelimiter("\\A").next();
        System.out.println(responseBody.substring(responseBody.indexOf("<title>") + 7, responseBody.indexOf("</title>")));

    } catch (IOException ex) {
        ex.printStackTrace();
    } finally {
        try {
            response.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-14
    • 2021-05-23
    • 2019-11-07
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多