java.net.URL timeout is unlimited by default

In Java, network applications can be developed through the URLConnection class or HttpURLConnection class, which are internally implemented through the java.net.URL class. The timeout for URLConnection connection and reading can be set through the URLConnection.setConnectTimeout() method and the URLConnection.setReadTimeout() method.
 

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

URLConnection connection = url.openConnection();

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

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

​

Among them, setConnectTimeout() sets the connection timeout in milliseconds.

setReadTimeout() sets the timeout for reading data, in milliseconds

Both methods are optional. If no timeout is set, the system default timeout will be used. Java's default timeout is infinite, that is, there is no limit to the timeout. Therefore, during development, a reasonable timeout should be set according to the actual situation to avoid problems caused by long wait times for the program due to network failures and other reasons.

For example: directly using new Url().openStream() will cause unlimited timeout problems

Source code:

 Test timeout:

You can use the website httpstat.us to test the timeout of URL requests.

The website provides some test URLs that simulate network requests with different delays.

For example, you can use the URL http://httpstat.us/200?sleep=5000 to simulate a request with a 5-second delay, where the sleep parameter indicates the number of milliseconds to sleep. Set the connection timeout and read timeout to 4 seconds, the code is as follows:

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());
        }
    }
}

Running this code will output "timeout error: connect timed out" after 4 seconds, indicating that the connection has timed out. If you change the connection timeout and read timeout to 6 seconds, you can receive a "statusCode=200" response, indicating that the request is successful.

Guess you like

Origin blog.csdn.net/weixin_42736075/article/details/129885479