gpt4 book ai didi

flutter - 在 flutter 中收到完整 header 之前关闭连接

转载 作者:行者123 更新时间:2023-12-02 18:17:46 24 4
gpt4 key购买 nike

我在尝试使用我的 API 时遇到问题,在跟进这个问题后我陷入了困境,我尝试了不同版本的不同模拟器,但问题仍然存在。

错误:

DioError [DioErrorType.other]: HttpException: Connection closed before full header was received, uri = http://10.0.2.2:7108/Users/authenticate

flutter 医生

enter image description here

HTTP 发布

class AuthenticateRemoteApi extends AuthenticateGateway {
final AuthenticateMapper _authenticateMapper = AuthenticateMapper();

@override
Future<SesionUser> login(Authenticate user) async {
var dio = Dio();
dio.options.headers['content-Type'] = 'application/json';
String url = 'http://10.0.2.2:7108/Users/authenticate';

try {
Response response = await dio.post(url, data: authenticateModelToJson(user));
return _authenticateMapper.fromMap(jsonDecode(response.data));
} catch (e) {
throw Exception(e);
}
}
}

最佳答案

我通过创建这个拦截器来解决这个问题。

它的想法是当遇到这个随机错误时只是重试请求。

/// Interceptor
class RetryOnConnectionChangeInterceptor extends Interceptor {
final Dio dio;

RetryOnConnectionChangeInterceptor({
required this.dio,
});

@override
void onError(DioError err, ErrorInterceptorHandler handler) async {
if (_shouldRetryOnHttpException(err)) {
try {
handler.resolve(await DioHttpRequestRetrier(dio: dio).requestRetry(err.requestOptions).catchError((e) {
handler.next(err);
}));
} catch (e) {
handler.next(err);
}
} else {
handler.next(err);
}

}

bool _shouldRetryOnHttpException(DioError err) {
return err.type == DioErrorType.other &&
((err.error is HttpException && err.message.contains('Connection closed before full header was received')));
}
}

/// Retrier
class DioHttpRequestRetrier {
final Dio dio;

DioHttpRequestRetrier({
required this.dio,
});

Future<Response> requestRetry(RequestOptions requestOptions) async {
return dio.request(
requestOptions.path,
cancelToken: requestOptions.cancelToken,
data: requestOptions.data,
onReceiveProgress: requestOptions.onReceiveProgress,
onSendProgress: requestOptions.onSendProgress,
queryParameters: requestOptions.queryParameters,
options: Options(
contentType: requestOptions.contentType,
headers: requestOptions.headers,
sendTimeout: requestOptions.sendTimeout,
receiveTimeout: requestOptions.receiveTimeout,
extra: requestOptions.extra,
followRedirects: requestOptions.followRedirects,
listFormat: requestOptions.listFormat,
maxRedirects: requestOptions.maxRedirects,
method: requestOptions.method,
receiveDataWhenStatusError: requestOptions.receiveDataWhenStatusError,
requestEncoder: requestOptions.requestEncoder,
responseDecoder: requestOptions.responseDecoder,
responseType: requestOptions.responseType,
validateStatus: requestOptions.validateStatus,
),
);
}
}

用法:将此拦截器 [RetryOnConnectionChangeInterceptor] 添加到您的 Dio 客户端实例

关于flutter - 在 flutter 中收到完整 header 之前关闭连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71343893/

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