设置HTTPClient get()请求的超时

编程入门 行业动态 更新时间:2024-10-23 11:32:37
本文介绍了设置HTTPClient get()请求的超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

此方法提交一个简单的HTTP请求并调用成功或错误回调就好了:

This method submits a simple HTTP request and calls a success or error callback just fine:

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应用或多或少会立即调用errorCallback。

If the server isn't running, the Android-app more or less instantly calls the errorCallback.

在iOS上,errorCallback会花费很长的时间-超过20秒-直到获得任何回调

On iOS, the errorCallback takes a very long period of time - more than 20 seconds - until any callback gets called.

我可以为HttpClient()设置等待服务器端返回回复的最大秒数-如果有的话?

推荐答案

有两种不同的方法可以在Dart中配置此行为

There are two different ways to configure this behavior in Dart

您可以使用 Future.timeout 方法。在给定的持续时间过去之后,这将通过引发 TimeoutException 来短路。

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上设置超时

您还可以使用 HttpClient.connectionTimeout 。设置超时后,这将应用于同一客户端发出的所有请求。当请求超过此超时时,将抛出 SocketException 。

final client = new HttpClient(); client.connectionTimeout = const Duration(seconds: 5);

更多推荐

设置HTTPClient get()请求的超时

本文发布于:2023-11-08 13:42:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569532.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:HTTPClient

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!