Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to java.net.URL for custom timeout setting

Tags:

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.

like image 284
Vishwanath Avatar asked Mar 18 '11 12:03

Vishwanath


People also ask

How to override the default timeout value for a Java web application?

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.

What is HTTP connection timeout in Java?

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.

How to set timeouts for all connections made from the JVM?

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.

How do I set the session timeout in Java?

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.


2 Answers

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?

like image 96
WhiteFang34 Avatar answered Sep 17 '22 09:09

WhiteFang34


A common replacement is the Apache Commons HttpClient, it gives much more control over the entire process of fetching HTTP URLs.

like image 38
Joachim Sauer Avatar answered Sep 19 '22 09:09

Joachim Sauer