天天看點

3.1.5 Jsoup逾時設定

在網絡異常的情況下,可能會發生連接配接逾時,進而導緻程式僵死而不再繼續往下執行。在Jsoup請求URL時,如果發生連接配接逾時的情況,則會抛出下圖所示的異常資訊。

3.1.5 Jsoup逾時設定
//程式3-8
public class JsoupConnectUrl {
    public static void main(String[] args) throws IOException {
        //通過Jsoup建立和url的連接配接
        Connection connection = Jsoup.connect("https://searchcustomerexperience.techtarget.com/info/news");
        //擷取網頁的Document對象
        Document document = connection.timeout(10*1000).get();
        //輸出HTML
        System.out.println(document.html());
    }
}      
//程式3-9
public class JsoupConnectUrl {
    public static void main(String[] args) throws IOException {
        //擷取響應
        Connection.Response response = Jsoup.connect("https://searchcustomerexperience.techtarget.com/info/news").method(Connection.Method.GET).timeout(10*1000).execute();
        //擷取響應狀态碼
        int statusCode = response.statusCode();
        //判斷響應狀态碼是否為200
        if (statusCode == 200) {
            //通過這種方式可以獲得響應的HTML檔案
            String html = new String(response.bodyAsBytes(),"gbk");
            //擷取html内容,但對應的是Document類型
            Document document = response.parse();
            //這裡html和document資料是一樣的,但document是經過格式化的
            System.out.println(document);
            System.out.println(html);
        }
    }
}