Need timeout setting for remote data request made using java.net.URL class. After some googling found out that there are two system properties which can be used to set timeout for URL class as follows.
sun.net.client.defaultConnectTimeout
sun.net.client.defaultReadTimeout
I don't have control over all the systems and don't want everybody to keep setting the system properties. Is there any other alternative for making remote request which will allow me to set timeouts. Without any library, If available in java itself is preferable.
And you can override the default timeout value for an individual web application on the server. There are two ways to set session timeout for a Java web application: using XML or Java code.
Connection Timeout In Java HTTPClient, RestTemplate and URLConnection. Connection timeout is the time for which an HTTP client or Socket client waits, if the server doesn’t respond in that time or not found then the client closes the connection. HTTP also uses sockets internally.
You can set timeouts for all connections made from the jvm by changing the following System-properties: System.setProperty ("sun.net.client.defaultConnectTimeout", "10000"); System.setProperty ("sun.net.client.defaultReadTimeout", "10000"); Every connection will time out after 10 seconds.
Set session timeout using Java code. Since Java Servlet 4.0, you can programmatically set session time out for a web application by using the setSessionTimeout () method of the ServletContext interface, before the servlet context is initialized.
If you're opening a URLConnection
from URL
you can set the timeouts this way:
URL url = new URL(urlPath);
URLConnection con = url.openConnection();
con.setConnectTimeout(connectTimeout);
con.setReadTimeout(readTimeout);
InputStream in = con.getInputStream();
How are you using the URL
or what are you passing it to?
A common replacement is the Apache Commons HttpClient, it gives much more control over the entire process of fetching HTTP URLs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With