zoukankan      html  css  js  c++  java
  • jsoup-提示java.net.SocketTimeoutException:Read timed out

    使用Jsoup.connect(url).get()连接某网站时偶尔会出现

    java.net.SocketTimeoutException:Read timed out异常。

    原因是默认的Socket的延时比较短,而有些网站的响应速度比较慢,所以会发生超时的情况。

    解决方法:

    链接的时候设定超时时间即可。

    doc = Jsoup.connect(url).timeout(5000).get();

    5000表示延时时间设置为5s。

    测试代码如下:

    1,不设定timeout时:

    package jsoupTest;  
      
    import java.io.IOException;  
      
    import org.jsoup.*;  
    import org.jsoup.helper.Validate;  
    import org.jsoup.nodes.Document;  
    import org.jsoup.nodes.Element;  
    import org.jsoup.select.Elements;  
      
    public class JsoupTest {  
        public static  void main(String[] args) throws IOException{  
        String url = "http://www.weather.com.cn/weather/101010400.shtml";  
        long start = System.currentTimeMillis();  
        Document doc=null;  
        try{  
            doc = Jsoup.connect(url).get();  
        }  
        catch(Exception e){  
            e.printStackTrace();  
        }  
        finally{  
            System.out.println("Time is:"+(System.currentTimeMillis()-start) + "ms");  
        }  
        Elements elem = doc.getElementsByTag("Title");  
        System.out.println("Title is:" +elem.text());  
        }     
    }  

    有时发生超时:

    java.net.SocketTimeoutException: Read timed out

    2,设定了则一般不会超时

    package jsoupTest;  
      
    import java.io.IOException;  
      
    import org.jsoup.*;  
    import org.jsoup.helper.Validate;  
    import org.jsoup.nodes.Document;  
    import org.jsoup.nodes.Element;  
    import org.jsoup.select.Elements;  
      
    public class JsoupTest {  
        public static  void main(String[] args) throws IOException{  
        String url = "http://www.weather.com.cn/weather/101010400.shtml";  
        long start = System.currentTimeMillis();  
        Document doc=null;  
        try{  
            doc = Jsoup.connect(url).timeout(5000).get();  
        }  
        catch(Exception e){  
            e.printStackTrace();  
        }  
        finally{  
            System.out.println("Time is:"+(System.currentTimeMillis()-start) + "ms");  
        }  
        Elements elem = doc.getElementsByTag("Title");  
        System.out.println("Title is:" +elem.text());  
        }     
    }  
  • 相关阅读:
    网络编程基础
    windows下配置chromedriver
    Selenium和PhantomJS
    爬虫之正则表达式re模块
    Fiddler抓包工具总结
    使用jquery刷新当前页面
    关于requests.exceptions.ConnectionError: HTTPSConnectionPool的问题
    python的urllib学习
    安卓---Tabhost实现页面局部刷新--父页子页之间的传值
    安卓---右滑返回
  • 原文地址:https://www.cnblogs.com/hwaggLee/p/4738762.html
Copyright © 2011-2022 走看看