http - 如何在 Dart 中设置多部分请求的超时?

标签 http flutter dart

这是我的MultiPartRequest代码

var request =
            http.MultipartRequest("POST", Uri.parse(EMPLOYEE_PUNCH_IN_URL));

        request.fields['uid'] = userId;
        request.fields['location'] = location;
        request.fields['punchin_time'] = punchInTime;
        request.fields['punchin_location_name'] = address;

        var multiPartFile = await http.MultipartFile.fromPath(
            "photo", imageFile.path,
            contentType: MediaType("image", "$extension"));
        request.files.add(multiPartFile);
        http.StreamedResponse response = await request.send();

        var responseByteArray = await response.stream.toBytes();

        employeePunchInModel = standardSerializers.deserializeWith(
            EmployeePunchInModel.serializer,
            json.decode(utf8.decode(responseByteArray)));
        ......

我知道如何为正常的 http 请求设置超时。我已点击此链接

Set timeout for HTTPClient get() request

我尝试通过以下方式添加超时功能,但它不起作用,我的请求已完成

1.

 var multiPartFile = await http.MultipartFile.fromPath(
            "photo", imageFile.path,
            contentType: MediaType("image", "$extension")).timeout(const Duration(seconds: 1)); 

2.

http.StreamedResponse response = await request.send().timeout(const Duration(seconds: 1));

3.

var responseByteArray = await response.stream.toBytes().timeout(const Duration(seconds: 15));

但是以上超时都不起作用。

最佳答案

使用http package ,这是我的方法:

  1. 创建一个我们将用于 onTimeOut 回调的流式响应
StreamedResponse timeOutResponse({
  @required String httpMethod,
  @required dynamic error,
  @required String url,
}) { 
  Map<String, dynamic> body = {
    'any': 'value',   
    'you': 'want for $error',
  };

  int statusCode = 404;  
  Uri destination = Uri.parse(url);
  String json = jsonEncode(body);
  
  return StreamedResponse(
    Stream.value(json.codeUnits),
    statusCode,
    request: Request(httpMethod, destination),
  );
}
  • 使用 Mahesh Jamdade 中修改后的 http 多部分函数回答
  • Future<http.Response> makeAnyHttpRequest(String url,
      Map<String, dynamic> body,
      {Function onTimeout,
      Duration duration = const Duration(seconds: 10)}) async {
    
         final request = http.MultipartRequest(
             'POST',
              Uri.parse('$url'),
           );
         
         final res = await request.send().timeout(
             duration,
             onTimeout: () {
               return timeOutResponse(
                 httpMethod: 'MULTIPART POST',
                 error: 'Request Time Out',
                 url: url,
               );
             },
           );
    
         return await http.Response.fromStream(res);
      }
    

    这样,您就可以返回 onTimeOut Http Response,而不是超时异常。

    关于http - 如何在 Dart 中设置多部分请求的超时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58247103/

    相关文章:

    dart - 为什么这个 bloc getter 在 null 上被调用?

    java - URLConnection.getHeaderFields() 返回 Map<String,List<String>> 的意义是什么

    php - $_POST 作为 $key => $value 使用复选框

    c++ - 使用 Qt 和 QNetworkRequest 恢复失败的 HTTP 下载

    flutter - 如何在flutter中实现Log base 2?

    android - 基于 Android 示例的 Flutter 应用程序在 BOOT_COMPLETED 上自动启动不起作用

    http - GET 和 POST 方法的独立 Flask 路由

    flutter - 如何在我 flutter 的电子商务应用程序中添加货币转换器?

    image - 检查图像 Assets 是否存在( flutter )

    flutter - 运行滑动启动后模棱两可的导入