java.net.URL超时时间默认无限制问题

Java中可以通过URLConnection类或者HttpURLConnection类来开发网络应用,它们内部又是通过java.net.URL类来实现的。可以通过URLConnection.setConnectTimeout()方法和URLConnection.setReadTimeout()方法来设置URLConnection连接和读取的超时时间。
 

​
URL url = new URL("Example Domain");

URLConnection connection = url.openConnection();

connection.setConnectTimeout(5000); //连接超时时间5秒

connection.setReadTimeout(10000); //读取数据的超时时间10秒

​

其中setConnectTimeout()设置连接超时时间,单位毫秒

setReadTimeout()设置读取数据的超时时间,单位毫秒

这两个方法都是可选的,如果不设置超时时间,就会使用系统默认的超时时间。  Java默认的超时时间是无限大,也就是不限制超时时间。所以在开发中,应该根据实际情况设置合理的超时时间,避免因网络故障等原因导致程序长时间等待而出现问题。

例如:直接使用new Url().openStream()就会导致超时无限制问题

源码:

 测试超时时间:

可以使用 httpstat.us 这个网站来测试URL请求的超时时间。

该网站提供了一些测试URL,可以模拟不同延迟的网络请求。

例如,可以使用URL http://httpstat.us/200?sleep=5000 来模拟延迟5秒的请求,其中的sleep参数表示需要睡眠的毫秒数。设置连接超时和读取超时时间为4秒,代码如下所示:

import java.net.*;

public class TimeoutTest {
    public static void main(String[] args) {
        try {
            URL url = new URL("http://httpstat.us/200?sleep=5000");
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(4000); //连接超时时间4秒
            conn.setReadTimeout(4000); //读取数据的超时时间4秒
            conn.setRequestMethod("GET");
            conn.connect();
            int statusCode = conn.getResponseCode();
            System.out.println("statusCode=" + statusCode);
        } catch (Exception e) {
            System.out.println("timeout error: " + e.getMessage());
        }
    }
}

运行该代码,将会在4秒后输出"timeout error: connect timed out",表明连接超时了。将连接超时和读取超时时间改成6秒,则可以收到"statusCode=200"的响应,表明请求成功。

猜你喜欢

转载自blog.csdn.net/weixin_42736075/article/details/129885479
今日推荐