HttpURLConnection超时设置
如果 URL 的连接时间超过 5 秒,我想返回 false - 使用 Java 怎么可能?这是我用来检查 URL 是否有效的代码
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
I want to return false if the URL takes more then 5 seconds to connect - how is this possible using Java? Here is the code I am using to check if the URL is valid
HttpURLConnection.setFollowRedirects(false);
HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
con.setRequestMethod("HEAD");
return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
HttpURLConnection
有一个 setConnectTimeout 方法。只需将超时设置为 5000 毫秒,然后捕获 java.net.SocketTimeoutException
您的代码应如下所示:
HttpURLConnection
has a setConnectTimeout method.Just set the timeout to 5000 milliseconds, and then catch
java.net.SocketTimeoutException
Your code should look something like this:
你可以这样设置超时,
You can set timeout like this,
如果 HTTP 连接没有超时,您可以在后台线程本身(AsyncTask、Service 等)中实现超时检查器,以下类是自定义 AsyncTask 的示例,该任务在一定时间后超时
A Sample for this
If the HTTP Connection doesn't timeout, You can implement the timeout checker in the background thread itself (AsyncTask, Service, etc), the following class is an example for Customize AsyncTask which timeout after certain period
A Sample for this
可以设置系统属性 sun.net.client.defaultConnectTimeout。该值以毫秒为单位。这将为每个请求设置默认超时 -
通过在 JVM 选项中设置 -
Dsun.net.client.defaultConnectTimeout=5000
或在 java 代码中
设置- System.setProperty("sun.net.client.defaultConnectTimeout", "5000") ;
The System property sun.net.client.defaultConnectTimeout can be set. The value is in milliseconds. This will set a default timeout for each request-
Either by setting in JVM options-
-Dsun.net.client.defaultConnectTimeout=5000
OR in java code-
System.setProperty("sun.net.client.defaultConnectTimeout", "5000");
我可以通过添加简单的行来获得此类类似问题的解决方案
我的要求是知道响应代码,为此只需获取元信息就足够了,而不是获取完整的响应正文。
默认请求方法是 GET,这需要很长时间才能返回,最后抛出 SocketTimeoutException。当我将请求方法设置为 HEAD 时,响应速度相当快。
I could get solution for such a similar problem with addition of a simple line
My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.
Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.