这是我的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 ,这是我的方法:
- 创建一个我们将用于
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/