java不加载网页获取标题的两种办法

发布于:2025-07-05 ⋅ 阅读:(16) ⋅ 点赞:(0)

Java获取网站的title
在Web开发过程中,有时我们需要获取网站的标题(title)信息。Java提供了一种简单的方法来实现这一功能。本文将介绍如何使用Java获取网站的标题,并提供完整的代码示例。

1. 使用Jsoup获取网页标题
然后,你可以使用以下代码来获取网页的标题:

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
 
public class WebTitleFetcher {
    public static void main(String[] args) {
        String url = "http://www.example.com"; // 你要获取标题的网页URL
        try {
            // 获取网页的HTML内容
            Document doc = Jsoup.connect(url).get();
            // 获取HTML中的title标签内容,即为网页标题
            String title = doc.title();
            System.out.println("网页标题: " + title);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 使用Java的URL类
Java的URL类提供了访问URL资源的方法。我们可以使用URL类来获取网站的标题。下面是一个简单的示例代码:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class GetWebsiteTitle {
    public static void main(String[] args) {
        String url = " // 要获取标题的网站URL

        try {
            URL website = new URL(url);
            URLConnection connection = website.openConnection();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains("<title>")) {
                    int startIndex = line.indexOf("<title>") + 7;
                    int endIndex = line.indexOf("</title>");
                    String title = line.substring(startIndex, endIndex);
                    System.out.println("Website Title: " + title);
                    break;
                }
            }

            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


在示例代码中,我们首先创建一个URL对象,然后使用openConnection()方法打开URL连接。接下来,我们使用getInputStream()方法获取URL资源的输入流,并创建一个BufferedReader来读取输入流中的数据。我们逐行读取数据,如果某一行包含<title>标签,则提取出title内容并打印出来。


网站公告

今日签到

点亮在社区的每一天
去签到