如果建立连接,会在15秒后关闭(如果我错了请告诉我连接关闭时间),并且空闲时间无法延长。在我的情况下,向同一个域发出多个请求并且需要持久连接,这意味着即使在 15 秒后也应该保持连接。是否有其他属性可以用来实现此目的?
在建立连接之前,如果发出多个请求,则每个请求都需要时间来建立连接。有没有办法避免这种情况并减少所有请求所需的时间?例如,在下面的屏幕截图中,在建立连接之前,向同一域发出了 4 个请求,每个请求大约需要 2 秒才能建立连接。有没有办法减少这个时间?
注意:我尝试使用 http 和 http_client_helper 包
为 Future 的响应设置超时可以帮助您做到这一点。所以你可以有类似的东西
final Response response = await HttpClientHelper(...).timeout(const Duration(seconds: 20));
此链接答案提供了有关处理连接超时和每个请求的更多详细信息。如果它回答了您的问题,请告诉我。
正如 Dharanidharan 所指出的,上述建议可以让你处理建立连接所需的时间。要在建立连接后管理空闲时间,我们需要使用HttpClient类。这使我们能够访问低级功能:
注意:HttpClient 提供低级 HTTP 功能。我们推荐 用户从更适合开发人员且可组合的 API 开始 包:http。
正如OP关于 idleTimeout 持续时间所述,
The default value is 15 seconds.
但是使用 HttpClient 类的idleTimeout 属性允许我们有机会修改这个值。
HttpClient client = HttpClient();
Future<String> get(String url) async {
String responseJson;
try {
client.idleTimeout = const Duration(minutes: 5);
// first future
// make a request to the url
HttpClientRequest request = await client.getUrl(Uri.parse(baseUrl + url));
// second future
// close the request to get the response data
HttpClientResponse response = await request.close();
// Process the response stream from the request
final stringData = await response.transform(utf8.decoder).join();
// Manage the processed response
responseJson = _response(stringData);
} on SocketException {
throw FetchDataException('');
} on ClientException {
throw FetchDataException('');
} catch (e) {
setState(() {
responseJson = e.toString();
});
}
return responseJson;
}
上述解决方案将idleTimeout从默认的15秒更改为5分钟。您可以阅读更多关于制作简单的 GET 请求的内容,以了解与 Helper 类交互的不同方式。
这里是 Dartpad 上的完整代码示例,适合任何想要快速构建测试的人。 (由于导入问题,可能无法直接在 Dartpad 中工作)。