抛出ConnectException之前的Java延迟

Jer*_*ome 3 java exception delay throw connectexception

我正在用Java编写一些代码来从网址下载内容,在我的配置中,一些下载应该由代理处理,而其他人则不需要处理.

所以我编写了这个代码(它可以工作)来下载所有的URL类型,但是我想减少抛出ConnectException之前的延迟时间,这样代码可以更快地执行.

URL global_url = new URL("http://google.com");
Scanner sc = null;
try { 
    sc = new Scanner(global_url.openStream());
}
catch (ConnectException e) {
    try {
        System.setProperty("http.proxyHost", "my.host");
        System.setProperty("http.proxyPort", "my.port");
        sc = new Scanner(global_url.openStream());
        System.setProperty("http.proxyHost", "");
        System.setProperty("http.proxyPort", "");
    }
    catch (ConnectException exc) {
        //Do stuff
    }
}
Run Code Online (Sandbox Code Playgroud)

现在需要约.抛出异常前10秒,我想把这个时间减少到最多2s或3s.

我可以得到一些帮助吗?谢谢 !

Jun*_*san 5

您可以像这样设置超时:

long connectTimeout = 3000;
URL global_url = new URL(urlPath);
URLConnection con = global_url.openConnection();
con.setConnectTimeout(connectTimeout);
Run Code Online (Sandbox Code Playgroud)

您可以在其中设置connectTimeout,以毫秒为单位.因为你需要3s超时所以设置为3000.