Alternative to java.net.URL for custom timeout set

2019-02-04 14:11发布

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.

标签: java url timeout
2条回答
爷的心禁止访问
2楼-- · 2019-02-04 14:38

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?

查看更多
叼着烟拽天下
3楼-- · 2019-02-04 14:54

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

查看更多
登录 后发表回答