dart – 设置HTTPClient get()请求的超时
发布时间:2020-12-14 14:50:55 所属栏目:百科 来源:网络整理
导读:此方法提交一个简单的HTTP请求并调用成功或错误回调就好了: void _getSimpleReply( String command,callback,errorCallback ) async { try { HttpClientRequest request = await _myClient.get( _serverIPAddress,_serverPort,'/' ); HttpClientResponse re
此方法提交一个简单的HTTP请求并调用成功或错误回调就好了:
void _getSimpleReply( String command,callback,errorCallback ) async { try { HttpClientRequest request = await _myClient.get( _serverIPAddress,_serverPort,'/' ); HttpClientResponse response = await request.close(); response.transform( utf8.decoder ).listen( (onData) { callback( onData ); } ); } on SocketException catch( e ) { errorCallback( e.toString() ); } } 如果服务器没有运行,Android-app或多或少会立即调用errorCallback. 在iOS上,errorCallback需要很长一段时间 – 超过20秒 – 直到调用任何回调. 我可以为HttpClient()设置一个等待服务器端返回回复的最大秒数 – 如果有的话? 解决方法
在Dart中有两种不同的方法来配置此行为
设置每个请求超时 您可以使用 try { final request = await client.get(...); final response = await request.close() .timeout(const Duration(seconds: 2)); // rest of the code ... } on TimeoutException catch (_) { // A timeout occurred. } on SocketException catch (_) { // Other exception } 在HttpClient上设置超时 您还可以使用 final client = new HttpClient(); client.connectionTimeout = const Duration(seconds: 5); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |