gpt4 book ai didi

flutter - 当我设置超时持续时间时,没有互联网连接的未处理的套接字异常

转载 作者:行者123 更新时间:2023-12-03 03:07:19 25 4
gpt4 key购买 nike

我使用简单的方法从互联网“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 块中关闭它,发生同样的错误并且应用程序崩溃

the image shows the error when the socket exception is thrown and unhandled

它按预期捕获超时异常,但又过了 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...
}

关于flutter - 当我设置超时持续时间时,没有互联网连接的未处理的套接字异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57182940/

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