循环内的 HttpURLConnection
我正在尝试连接到一个我知道存在但不知道何时存在的 URL。 我无权访问该服务器,因此无法更改任何内容来接收事件。
实际的代码是这样的。
URL url = new URL(urlName);
for(int j = 0 ; j< POOLING && disconnected; j++){
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_NOT_MODIFIED){
//Some work
}else{
//wait 3s
Thread.sleep(3000);
}
}
Java 不是我最擅长的技能,我不确定从性能的角度来看这段代码是否良好。 我每 3 秒打开一个新连接?或者连接被重用?
如果我调用disconnect(),我确保循环中没有打开新连接,但是......这会影响性能吗?
建议?知道 URL 存在的快速/最佳方法是什么?
I'm trying to connect to one URL that I know that exist but I don't know when.
I don't have access to this server so I can't change anything to receive a event.
The actual code is this.
URL url = new URL(urlName);
for(int j = 0 ; j< POOLING && disconnected; j++){
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
int status = connection.getResponseCode();
if(status == HttpURLConnection.HTTP_OK || status == HttpURLConnection.HTTP_NOT_MODIFIED){
//Some work
}else{
//wait 3s
Thread.sleep(3000);
}
}
Java not is my best skill and I'm not sure if this code is good from the point of view of performance.
I'm opening a new connection every 3 seconds? or the connection is reused?
If I call to disconnect() I ensure that no new connections are open in the loop, but... it will impact in performance?.
Suggestions? What is the fast/best ways to know it a URL exist?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
1)一定要使用断开连接,您不希望有大量不使用的打开连接。丢弃不使用的资源是任何语言的基本做法。
2)我不知道每3秒打开和关闭新的网络连接是否会污染系统资源,唯一的检查方法就是尝试。
3) 如果“URL [不]存在”意味着服务器已关闭,您可能需要监视“ConnectException”。
1) Do use disconnect, you don't want numerous open connections you don't use. Discarding resources you don't use is a basic practice in any language.
2) I don't know if opening and closing new network connection every 3 seconds will pollute system resources, the only way to check it is to try.
3) You may want to watch for 'ConnectException', if by "URL [does not] exist" you mean server is down.
从性能的角度来看,这段代码还可以,它每次都会创建一个新连接。无论如何,如果您的循环中有一个 Thread.sleep(3000) ,您不必担心性能;)
如果您担心服务器端的连接使用情况,您可以查看apache HTTP 客户端,它有很多功能。我认为它默认处理保持活动连接。
This code is okay from a performance point of view, it will create a new connection each time. Anyway if you have a
Thread.sleep(3000)
in your loop, you shouldn't have to worry about performance ;)If you're concerned about connection usage on the server side, you can look into apache HTTP client, it has a lot of features. I think it handles keep alive connections by default.