- Jsoup SocketTimeoutException Read timed out Connect timed out fix
- How to fix Jsoup java.net.SocketTimeoutException: Read timed out exception?
- How to fix Jsoup java.net.SocketTimeoutException: Connect timed out exception?
- How to handle java.net.SocketTimeoutException
- How to solve?
- From Client side:
- Using try/catch/finally
- From Server side:
- How to Java SocketTimeoutException?
- Timeouts and how to handline in Java
- Connection timeout
- Socket timeout
- Read timeout
- Write timeout
- Apache Camel
- Rest Template
- WebClient
- Summary
- How to generate Simple Timeout Exception in Java?
- Suggested Articles.
Jsoup SocketTimeoutException Read timed out Connect timed out fix
Jsoup SocketTimeoutException read timed out, connect timed out example shows how to fix SocketTimeoutException while using Jsoup in Java. The example also shows how to set the timeout in Jsoup.
How to fix Jsoup java.net.SocketTimeoutException: Read timed out exception?
You may encounter “java.net.SocketTimeoutException: Read timed out” exception while using the Jsoup. Here is the program which gave me the exception.
The problem is the default Jsoup timeout which is 3 seconds. If you encounter the exception “java.net.SocketTimeoutException: Read timed out”, it means that time our program took to read the requested webpage was exceeded the default timeout time (3 seconds).
You need to increase the timeout Jsoup uses to fix the problem using timeout method of Connection class.
This method sets the connect and read timeout both. Please note that the timeout is in milliseconds.
How to fix Jsoup java.net.SocketTimeoutException: Connect timed out exception?
Another exception Jsoup may throw is “java.net.SocketTimeoutException: Connect timed out”. This exception means the time taken by our program to connect to the requested URL exceeded the timeout Jsoup uses.
Here is how to fix/resolve the “Connect time out” exception.
1) Make sure you are connected to the internet. Try to open the same URL in the browser and see if it opens the page.
2) Specify Jsoup connection time out before getting the document as given below.
How to handle java.net.SocketTimeoutException
Your Java socket is timing out (throws java.net.SocketTimeoutException: Connection timed out) means that it takes too long to get respond from other device and your request expires before getting response.
How to solve?
A developer can pre-set the timeout option for both client and server operations.
From Client side:
You can effectively handle it from client side by define a connection timeout and later handle it by using a try/catch/finally block. You can use the connect(SocketAddress endpoint, int timeout) method and set the timeout parameter:
Socket socket = new Socket(); SocketAddress socketAddress = new InetSocketAddress(host, port); socket.connect(socketAddress, 12000); //12000 are milli seconds
Note: If the timeout elapses before the method returns, it will throw a SocketTimeoutException.
If you are using OkHttp Client then you can add:
OkHttpClient client = new OkHttpClient(); client.setConnectTimeout(60, TimeUnit.SECONDS); client.setReadTimeout(60, TimeUnit.SECONDS); client.setWriteTimeout(60, TimeUnit.SECONDS);
If you are using OkHttp3 then you must do it using the builder:
OkHttpClient.Builder builder = new OkHttpClient.Builder(); builder.connectTimeout(60, TimeUnit.SECONDS); builder.readTimeout(60, TimeUnit.SECONDS); builder.writeTimeout(60, TimeUnit.SECONDS); client = builder.build();
Using try/catch/finally
If you are a developer, so you can surround the socket connection part of your code in a try/catch/finally and handle the error in the catch. You might try connecting a second time, or try connecting to another possible socket, or simply exit the program cleanly.
From Server side:
From server side you can use the setSoTimeout(int timeout) method to set a timeout value. The timeout value defines how long the ServerSocket.accept() method will block:
How to Java SocketTimeoutException?
A socket is one end-point of a logical link between two computer applications. In order to establish a connection to the server from the remote client, the socket constructor is invoked, which instantiates a socket object. This operation blocks all other processes until a successful connection is made. However, if the connection isn’t successful after a period of time, the program throws a ConnectionException with a message:
This exception is occurring on following condition.
- Server is slow and default timeout is less, so just put timeout value according to you.
- Server is working fine but timeout value is for less time. so change the timeout value.
It is important to note that after this exception is thrown the socket remains valid , so you can retry the blocking call or do whatever you want with the valid socket.
So to avoid this exception in another way, you should keep the connection be alive using the method Socket.setKeepAlive() method although possibly you have not used the method setTimeout() , meaning asking the socket to unlimited block to receive.
Timeouts and how to handline in Java
In this article we will try to cover why it’s important to define timeouts for out bound rest calls. Before configuring any timeout let’s understand below some common exceptions for http outbound calls,
Connection timeout
maximum time to wait for the other side to answer «yes, I’m here, let’s talk» when creating a new connection, (ConnectTimeout eventually calls socket.connect(address, timeout), If the connection is not established within the ConnectTimeout specified by you or the library you are using then, you get an error ‘connect timedout
Socket timeout
Is the timeout for waiting for data or, put differently, a maximum period inactivity between two consecutive data packets
Read timeout
Read timeout can happen when there is successful connection established between client and the server and there is an inactivity between data packets while waiting for the server response.
Write timeout
Similar to Read timeout, write timeout can happen when there is successful connection established between client and server, and there is inactivity between data packets while sending the request to the server. The important topic to remember here is that based on the choice of library we use for outbound calls it’s very important that we configure the properties to handle the above mentioned one’s and handle the exception gracefully.
Apache Camel
If we are using Apache Camel ‘http’ component to make the outbound calls then we can configure these properties in following ways, please note that if we don’t define this properties the default values is -1! means connection will never timeout and can have advert effect on the application performance overall. camel.property
http.urlProxy = http4://ThirdPartyServers?throwExceptionOnFailure=false&httpClient.socketTimeout=$&httpClient.connectTimeout=$
@Override public void configure() throws Exception configureTimeout(); > private void configureTimeout() HttpComponent httpComponent = getContext().getComponent("http4", HttpComponent.class); httpComponent.setConnectionTimeToLive(VALUE_IN_MILI);// for closing the idle connection - in milliseconds httpComponent.setSocketTimeout(VALUE_IN_MILI); //socket timeout - in milliseconds httpComponent.setConnectTimeout(VALUE_IN_MILI); // connection timeout - in milliseconds*/ >
Rest Template
final RequestConfig requestConfig = RequestConfig.custom() .setConnectionRequestTimeout(VALUE_IN_MILI) .setConnectTimeout(VALUE_IN_MILI) .setSocketTimeout(VALUE_IN_MILIs) .build(); final HttpClient httpClient = HttpClients.custom() .setConnectionTimeToLive(VALUE_IN_MILI, SECONDS) .setRetryHandler((IOException exception, int executionCount, HttpContext context) -> return executionCount 3; >) .setServiceUnavailableRetryStrategy(new DefaultServiceUnavailableRetryStrategy(3, 1)) .setDefaultRequestConfig(requestConfig) .build(); final RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));
WebClient
public WebClient getWebClient() HttpClient httpClient = HttpClient.create() .tcpConfiguration(client -> client.option(ChannelOption.CONNECT_TIMEOUT_MILLIS, VALUE_IN_MILI) .doOnConnected(conn -> conn .addHandlerLast(new ReadTimeoutHandler(rest.timeout.millis)) .addHandlerLast(new WriteTimeoutHandler(rest.timeout.millis)))); ClientHttpConnector connector = new ReactorClientHttpConnector(httpClient.wiretap(true)); return WebClient.builder() .baseUrl("http://localhost:3000") .clientConnector(connector) .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) .build(); >
Summary
All in all it’s very important to configure these values i.e. connection timeout, read timeout, socket timeout etc so as to terminate the connections after waiting for a specific amount of time rather keeping the connection open indefinitely which can bring issues to overall application performance and stability.
How to generate Simple Timeout Exception in Java?
In this tutorial we will generate Timeout error calling Google.com with simple 10 millisecond delay. CrunchifyGenerateTimeout is a public call in which we are calling google.com using connection.connect() .
package crunchify.com.tutorial; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; /** * @author Crunchify.com * Program: How to Generate Simple TimeoutException for a specific IP in Java * Version: 1.0.1 * */ public class CrunchifyGenerateTimeout < public static void main(String[] args) throws Exception < new CrunchifyGenerateTimeout(); >public CrunchifyGenerateTimeout() < try < String myUrl = "https://google.com/"; // myUrl = URLEncoder.encode(myUrl, "UTF-8"); String results = crunchifyCallURL(myUrl); System.out.println(results); >catch (Exception e) < e.printStackTrace(); >> /** * Just return a result of URL call. * * @param crunchifyURL * @return * @throws Exception */ private String crunchifyCallURL(String crunchifyURL) throws Exception < URL crunchURL = null; BufferedReader crunchReader = null; StringBuilder crunchBuilder; try < // create the HttpURLConnection crunchURL = new URL(crunchifyURL); HttpURLConnection connection = (HttpURLConnection) crunchURL.openConnection(); // Let's make GET call connection.setRequestMethod("GET"); // Current Timeout 10 milliseconds - to generate Timeout Error connection.setReadTimeout(10); connection.connect(); // Simply read result and print line crunchReader = new BufferedReader(new InputStreamReader(connection.getInputStream())); crunchBuilder = new StringBuilder(); String eachLine = null; while ((eachLine = crunchReader.readLine()) != null) < crunchBuilder.append(eachLine + "\n"); >return crunchBuilder.toString(); > catch (Exception et) < et.printStackTrace(); throw et; >finally < if (crunchReader != null) < try < crunchReader.close(); >catch (IOException ioException) < ioException.printStackTrace(); >> > > >
Just run above program as Java application and you will be able to generate TimeoutException in Eclipse console.
If you increase ReadTimeout to 1000 milliseconds then you won’t be able to regenerate exception.
java.net.SocketTimeoutException: Read timed out at java.base/java.net.SocketInputStream.socketRead0(Native Method) at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171) at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141) at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425) at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:154) at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1031) at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1429) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413) at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:163) at crunchify.com.tutorial.CrunchifyGenerateTimeout.doHttpUrlConnectionAction(CrunchifyGenerateTimeout.java:60) at crunchify.com.tutorial.CrunchifyGenerateTimeout.(CrunchifyGenerateTimeout.java:29) at crunchify.com.tutorial.CrunchifyGenerateTimeout.main(CrunchifyGenerateTimeout.java:20) java.net.SocketTimeoutException: Read timed out at java.base/java.net.SocketInputStream.socketRead0(Native Method) at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116) at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171) at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141) at java.base/sun.security.ssl.SSLSocketInputRecord.read(SSLSocketInputRecord.java:425) at java.base/sun.security.ssl.SSLSocketInputRecord.decode(SSLSocketInputRecord.java:154) at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:1031) at java.base/sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:973) at java.base/sun.security.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1402) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1429) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1413) at java.base/sun.net.www.protocol.https.HttpsClient.afterConnect(HttpsClient.java:567) at java.base/sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:185) at java.base/sun.net.www.protocol.https.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:163) at crunchify.com.tutorial.CrunchifyGenerateTimeout.doHttpUrlConnectionAction(CrunchifyGenerateTimeout.java:60) at crunchify.com.tutorial.CrunchifyGenerateTimeout.(CrunchifyGenerateTimeout.java:29) at crunchify.com.tutorial.CrunchifyGenerateTimeout.main(CrunchifyGenerateTimeout.java:20)
If you liked this article, then please share it on social media. Have a question or suggestion? Please leave a comment to start the discussion. 👋