![](/img/trans.png)
[英]Why the first call to constructor takes 10 times more time than other ones?
[英]UrlConnection API Call takes much more time the first time, then onwards it is comparable to curl.exe or postman
I have observed that one of my api is taking much more time if called through Java (URLConnection or Apache Http Client or OKHttp) for the first time. 对于随后的调用,时间要少得多。
虽然 Postman 或 curl.exe 花费的时间非常少(与 java 的第二次迭代相比)
对于我的机器,第一次开销约为 2 秒。 但在某些机器上,这是第一次上升到大约 5-6 秒。 此后,往返时间约为 300 毫秒。
这是我的示例代码:
public static String DoPostUsingURLConnection(String s_uri) throws Exception {
try {
URL uri = new URL(s_uri);
HttpURLConnection connection = (HttpURLConnection) uri.openConnection();
// Logger.log("Opened Connection");
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
connection.setRequestProperty("Authorization", authorizationHeader);
// Create the Request Body
try (OutputStream os = connection.getOutputStream()) {
byte[] input = jsonRequestBody.getBytes("utf-8");
os.write(input, 0, input.length);
}
// Logger.log("Written Output Stream");
int responseCode = connection.getResponseCode();
InputStream is = null;
if (responseCode == HttpURLConnection.HTTP_OK)
is = connection.getInputStream();
else
is = connection.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(is));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine).append("\n");
;
}
in.close();
return response.toString();
} catch (Exception ex) {
return ex.getMessage();
} finally {
// Logger.log("Got full response");
}
这只是一个猜测。 但是 Http 连接的工作方式是,当您第一次调用它时,连接建立起来需要时间。 在那之后,Http 协议在一段时间内并没有真正关闭连接,因为期望会出现更多请求并且可以重新使用连接。 在您的情况下,您确实发送了重新使用先前创建的连接的后续请求,而不是重新建立它,这是扩展的。 我编写了自己的开源库,其中包含一个简单的 Http 客户端。 我注意到第一个请求比后续请求花费更长的时间的效果相同。 但这并不能解释为什么在 Postman 和 curl 中我们看不到相同的效果。 无论如何,如果您想解决这个问题并且您提前知道您的 URL,请在您的应用程序初始化时发送请求(您甚至可以在单独的线程中进行)。 这将解决你的问题。
如果您有兴趣查看我的库,这里是Javadoc 链接。 你可以在这里找到它作为 maven 工件和 github在这里。 关于库的文章,其中包含部分功能列表
您可以通过记录 OkHttp 连接事件来调查花费的时间。 https://square.github.io/okhttp/events/
如果您获得一个 IPv4 地址和 IPv6 并且其中一个超时而另一个成功,这将特别重要。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.