How to get page meta (title, description, images) like facebook attach url using Regex in java

前端 未结 4 1652
孤城傲影
孤城傲影 2021-02-19 08:35

How to get page meta (title, description, images) like facebook attach url using Regex in .java

4条回答
  •  一整个雨季
    2021-02-19 09:10

    Here's a snippet that reads a web page and builds a little chunk of HTML that will display the Open Graph image, and Title to the right wrapping around the image. It falls back to using just html title if OG tags are missing, so it can work to represent all web pages.

    public static String parsePageHeaderInfo(String urlStr) throws Exception {
    
        StringBuilder sb = new StringBuilder();
        Connection con = Jsoup.connect(urlStr);
    
        /* this browseragant thing is important to trick servers into sending us the LARGEST versions of the images */
        con.userAgent(Constants.BROWSER_USER_AGENT);
        Document doc = con.get();
    
        String text = null;
        Elements metaOgTitle = doc.select("meta[property=og:title]");
        if (metaOgTitle!=null) {
            text = metaOgTitle.attr("content");
        }
        else {
            text = doc.title();
        }
    
        String imageUrl = null;
        Elements metaOgImage = doc.select("meta[property=og:image]");
        if (metaOgImage!=null) {
            imageUrl = metaOgImage.attr("content");
        }
    
        if (imageUrl!=null) {
            sb.append("");
        }
    
        if (text!=null) {
            sb.append(text);
        }
    
        return sb.toString();       
    }
    

提交回复
热议问题