flutter - 当我设置超时持续时间时,未处理的套接字异常没有互联网连接
问题描述
我使用简单的方法从 Internet 'http get request' 获取一些数据:
`Future<UserModel> getUser(int userId) async {
UserModel user;
try {
final response = await http.get(
"$_baseUrl/users/$userId",
)
.timeout(Duration(seconds: 5))
;
user = userModelFromJson(response.body);
return user;
} on TimeoutException catch (e) {
print('$e in authentication service');
throw e;
} on SocketException catch (e) {
print('$e in authentication service');
throw e;
} catch (e) {
print('$e in authentication service');
throw e;
}
}`
但是当我没有互联网连接时,它会向我显示该错误:
`Exception has occurred.
SocketException (SocketException: Failed host lookup:
'jsonplaceholder.typicode.com' (OS Error: No address associated with
hostname, errno = 7))`
每当我删除 .timeout(Duration(seconds:5)) 时,代码都可以正常工作,但是在很长一段时间(15-20)秒后捕获了套接字异常,以表明没有互联网连接,这就是我使用超时的原因,我试过了要使用多个包(http 中间件、http 助手、重试),我尝试使用 http.client 并在 finally 块中关闭它,并且发生相同的错误并且应用程序崩溃
它按预期捕获了超时异常,但又过了 10-15 秒后,它抛出了一个已处理的套接字异常,为什么它会抛出这个套接字异常,我该怎么做才能避免这种情况?
解决方案
如果你想用 http 包实现超时,可以这样做:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:http/io_client.dart' as http;
Future<void> login(String email, String password) async {
final ioClient = HttpClient();
client.connectionTimeout = const Duration(seconds: 5);
final body = { 'email': email, 'password': password };
final client = http.IOClient(ioClient);
http.Response res;
try {
res = await client
.post(
'$url/login',
headers: {'Content-Type': 'application/json'},
body: jsonEncode(body));
} on SocketException catch (e) {
// Display an alert, no internet
} catch (err) {
print(err);
return null;
}
// Do something with the response...
}
推荐阅读
- multithreading - 如何在groovy中实现多线程?
- r - 使用公式中使用的参数创建函数
- javascript - 使用javascript在空格后反转数组
- c++ - 实现进程外 COM 服务器,每个调用进程一个服务器进程
- django - 如何修复“序列化器字段可能命名不正确,并且与 DRF 中“模型”实例上的任何属性或键不匹配
- r - 有没有办法在 for 循环中为数据框赋值?
- mapbox - 基于z-index将图层排序为baselayer,wms layer,tile layer
- excel - 删除/添加工作表事件 - VBA
- c++ - std::call_once,什么时候应该使用?
- c# - 如何从控制器返回多个文件,因为它在返回一个文件后停止?MVC