简体   繁体   English

java.net.URL替代自定义超时设置

[英]Alternative to java.net.URL for custom timeout setting

Need timeout setting for remote data request made using java.net.URL class. 需要使用java.net.URL类进行远程数据请求的超时设置。 After some googling found out that there are two system properties which can be used to set timeout for URL class as follows. 在一些谷歌搜索后发现有两个系统属性可用于设置URL类的超时,如下所示。

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本身可用是可取的。

If you're opening a URLConnection from URL you can set the timeouts this way: 如果您从URL打开URLConnection ,则可以通过以下方式设置超时:

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? 你是如何使用URL或者你传递的是什么?

一个常见的替代品是Apache Commons HttpClient ,它可以更好地控制获取HTTP URL的整个过程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM