循环内的 HttpURLConnection

发布于 2024-09-04 17:51:45 字数 666 浏览 6 评论 0原文

我正在尝试连接到一个我知道存在但不知道何时存在的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

物价感观 2024-09-11 17:51:45

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.

樱花细雨 2024-09-11 17:51:45

从性能的角度来看,这段代码还可以,它每次都会创建一个新连接。无论如何,如果您的循环中有一个 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文