gpt4 book ai didi

Java - url.openConnection() 和 httpsUrlConnection.connect() 首次调用时运行缓慢

转载 作者:行者123 更新时间:2023-12-02 10:43:00 25 4
gpt4 key购买 nike

我在编写Java程序时发现一个有趣的现象。

我创建了 3 个到 3 个不同 URL 的 https 连接,并且我发现当我为 调用 url.openConnection()httpsUrlConnection.connect() 时, >第一次,它们分别花费了近300ms1s来执行,而在第二次和第三次调用期间,它们花费了近0ms >.

造成这些性能差异的原因是什么?

顺便说一句,我可以做些什么来提高性能吗?

仅供引用,所有三个 httpsURLConnection 均如下所示(未显示 try-catch):

Url url = new URL("https://www.google.com");
Utils.logTime(logger);
HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();
Utils.logTime(logger);
httpsURLConnection.setRequestMethod("GET");
httpsURLConnection.setConnectTimeout(5 * 1000);
httpsURLConnection.setReadTimeout(5 * 1000);
httpsURLConnection.setRequestProperty(Utils.ACCEPT, Utils.ACCEPT_ALL);
httpsURLConnection.setRequestProperty(Utils.ACCEPT_ENCODING, Utils.GZIP);
httpsURLConnection.setRequestProperty(Utils.USER_AGENT, Utils.MOZILLA);
Utils.addCookiesToConnection(httpsURLConnection, cookieMap);
Utils.logTime(logger);
httpsURLConnection.connect();
Utils.logTime(logger);

正如你所假设的,Utils和cookieMap是我自己创建的一个类和一个HashMap,因此它们不应成为解决方案的重点。

有什么想法吗?提前致谢。

最佳答案

造成时间差异的原因可能是:第一次需要建立socket连接(从源ip到目标ip和端口)。一旦建立,同一个 TCP 连接就可以重复使用。这在网络编程中很正常。

为了提高效率并更好地控制连接池,我建议考虑 Apache HttpClient

关于Java - url.openConnection() 和 httpsUrlConnection.connect() 首次调用时运行缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52798487/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com