Android 通过网址url获取网址标题

大多数场景下,我们需要展示一个网页并获取标题时,我们会用webview去load这个url,在onReceiveTitle里获取它的标题。但在某些场景下,我们想直接拿到标题但并不想展示这个网页,毕竟webView也是很吃性能的。
首先我们得获取这个url的html文本,然后从html文本中截取出title,这里我们用两种方式来获取

第一种方式

获取html文本代码

public static String getHtmlContent(String urlpath) throws Exception {
        URL url = new URL(urlpath);
        HttpURLConnection conn=null;
        try {
            conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(6 * 1000);
            conn.setRequestMethod("GET");
            conn.setInstanceFollowRedirects(true);
            if (conn.getResponseCode() == 200) {
                LogUtil.logE("success===200");
                InputStream inputStream = conn.getInputStream();
                byte[] data = readStream(inputStream);
                String html = new String(data);
                return html;
            }else if(conn.getResponseCode()==301||conn.getResponseCode()==302){//重定向
                LogUtil.logE("重定向========"+conn.getResponseCode());
                String nestUrl=conn.getHeaderField("Location");
                LogUtil.logE("重定向==="+nestUrl);
                return getHtmlContent(nestUrl);
            }
        }catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //最后将conn断开连接
            if (conn != null) {
                conn.disconnect();
            }
        }
        return null;
    }
    public static byte[] readStream(InputStream inputStream) throws IOException {
        byte[] buffer = new byte[1024];
        int len = -1;
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        while ((len = inputStream.read(buffer)) != -1) {
            byteArrayOutputStream.write(buffer, 0, len);
        }

        inputStream.close();
        byteArrayOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

有些url的getResponseCode会返回301,302重定向,需要拿到重定向后的url继续获取html文本。拿到html文本后,截取title标签

    //截取title标签获取标题
    public static String getTitle(String html){
        LogUtil.logE("html==========="+html);
        if(!TextUtils.isEmpty(html)){
            int rightPoint=html.indexOf("</title>");
            if(rightPoint<0)return"";
            String sub =html.substring(0,rightPoint);
            int leftPoint=sub.lastIndexOf(">");
            if(leftPoint<0)return"";
            String title=sub.substring(leftPoint+1,sub.length());
            return title;
        }
        return "";
    }

第二种方式

第一种方式获取方式存在缺陷性,比如不同网站title的编码格式不一,有些网址截取出来的title是乱码。也有反馈说,有些网址conn.getResponseCode() == 200时,获取到的html文本是空。(这个我自己倒是没遇到过。。。)
这第二种方式是使用jsoup来获取。
添加依赖 compile 'org.jsoup:jsoup:1.9.2'
先得到head标签再拿到title标签

    public static String getWebTitle(String url){
        try {
            //还是一样先从一个URL加载一个Document对象。
            Document doc = Jsoup.connect(url).get();
            Elements links = doc.select("head");
            Elements titlelinks=links.get(0).select("title");
            return titlelinks.get(0).text();
        }catch(Exception e) {
            return "";
        }
    }

果然还是第三方叼,经实验, Document doc = Jsoup.connect(url).get()已经处理过重定向了。
个人推荐使用第二种方法。 PS:网络操作请在子线程处理 O_O !