射精一区欧美专区|国产精品66xx|亚洲视频一区导航|日韩欧美人妻精品中文|超碰婷婷xxnx|日韩无码综合激情|特级黄片一区二区|四虎日韩成人A√|久久精品内谢片|亚洲成a人无码电影

您現(xiàn)在的位置:首頁 > IT認(rèn)證 > JAVA >

Java基礎(chǔ)知識:java獲取網(wǎng)頁源代碼


要分析某個網(wǎng)頁中的代碼構(gòu)成,需要某個結(jié)點下的內(nèi)容。用此原始方法可以得到整個網(wǎng)頁的源碼。其實更簡單的方法是使用 WebClient 或 HtmlUtil 等開源方式 。

[java]  

public class HtmlParser {  

    public static String getHtmlContent(URL url, String encode) {  

        StringBuffer contentBuffer = new StringBuffer();  

  

        int responseCode = -1;  

        HttpURLConnection con = null;  

        try {  

            con = (HttpURLConnection) url.openConnection();  

            con.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");// IE代理進(jìn)行下載  

            con.setConnectTimeout(60000);  

            con.setReadTimeout(60000);  

            // 獲得網(wǎng)頁返回信息碼  

            responseCode = con.getResponseCode();  

            if (responseCode == -1) {  

                System.out.println(url.toString() + " : connection is failure...");  

                con.disconnect();  

                return null;  

            }  

            if (responseCode >= 400) // 請求失敗  

            {  

                System.out.println("請求失敗:get response code: " + responseCode);  

                con.disconnect();  

                return null;  

            }    InputStream inStr = con.getInputStream();  

            InputStreamReader istreamReader = new InputStreamReader(inStr, encode);  

            BufferedReader buffStr = new BufferedReader(istreamReader);  

  

            String str = null;  

            while ((str = buffStr.readLine()) != null)  

                contentBuffer.append(str);  

            inStr.close();  

        } catch (IOException e) {  

            e.printStackTrace();  

            contentBuffer = null;  

            System.out.println("error: " + url.toString());  

        } finally {  

            con.disconnect();  

        }  

        return contentBuffer.toString();  

    }  

  

    public static String getHtmlContent(String url, String encode) {  

        if (!url.toLowerCase().startsWith("")) {  

            url = "" + url;  

        }  

        try {  

            URL rUrl = new URL(url);  

            return getHtmlContent(rUrl, encode);  

        } catch (Exception e) {  

            e.printStackTrace();  

            return null;  

        }  

    }  

    public static void main(String argsp[]){  

        System.out.println(getHtmlContent("","utf-8")) ;  

          

    }  

}  

相關(guān)文章

無相關(guān)信息
更新時間2022-09-16 10:07:22【至頂部↑】
聯(lián)系我們 | 郵件: | 客服熱線電話:4008816886(QQ同號) | 

付款方式留言簿投訴中心網(wǎng)站糾錯二維碼手機(jī)版

電話:
付款方式   |   給我留言   |   我要糾錯   |   聯(lián)系我們