Google News
logo
Jsoup - Interview Questions
How do you set timeouts for Jsoup connections?
In Jsoup, you can set timeouts for connections to handle situations where the server may be slow to respond or the network connection is unreliable. Jsoup provides methods to configure both the connection timeout (the time to establish the connection) and the read timeout (the time to wait for data to be read from the server). Here's how you can set timeouts for Jsoup connections:

1. Setting Connection Timeout : You can set the connection timeout using the timeout() method when establishing the connection using Jsoup's connect() method. The timeout value is specified in milliseconds.
int connectionTimeoutMillis = 5000; // 5 seconds
Connection connection = Jsoup.connect("http://example.com")
                               .timeout(connectionTimeoutMillis);?

In this example, the connection timeout is set to 5 seconds (5000 milliseconds) for the connection to http://example.com.

2. Setting Read Timeout : You can set the read timeout using the timeout() method after establishing the connection. Again, the timeout value is specified in milliseconds.
int readTimeoutMillis = 10000; // 10 seconds
Connection connection = Jsoup.connect("http://example.com")
                               .timeout(readTimeoutMillis)
                               .get();?

In this example, the read timeout is set to 10 seconds (10000 milliseconds) for reading data from the server after the connection is established.

By setting appropriate connection and read timeouts, you can ensure that Jsoup connections don't hang indefinitely and that your application doesn't become unresponsive due to slow or unresponsive servers. Adjust the timeout values according to your specific requirements and the expected behavior of the server you're connecting to.
Advertisement