當我將資料發送到 API 時,我遇到了一個奇怪的錯誤。
當我發送和接收資料時,我有一些端點作業得很好。但其中之一給我帶來了一些麻煩。
我會盡力解釋。
因此,當我使用 HTTP 包通過 POST 方法發送資料物件時,發送的資料正在到達資料庫并被添加,但沒有從申請中回傳。
Future postCupomFiscal(CupomFiscal cupom) async {
log(jsonEncode(cupom.toJson()));
var config = await LojaConfigs.iniciarConfigs();
var url = Uri.parse('http://127.0.0.1:8082/api/v1/carga_venda');
var client = http.Client();
try {
var response = await client
.post(url,
headers: {
'Content-Type': 'application/json; charset=UTF-8',
'ambiente': '${config['ambiente']}',
'cnpj_loja': '${config['cnpj_loja']}',
'chave_acesso': '${config['chaveacesso']}',
'token': '${config['token']}'
},
body: jsonEncode(cupom.toJson()))
.timeout(const Duration(seconds: 15));
if (response.statusCode == 200 || response.statusCode == 201) {
return jsonDecode(response.body);
}
} on SocketException {
throw FetchDataException('Sem conex?o com a Internet.');
} on TimeoutException {
throw FetchDataException('Tempo excedido.');
} finally {
client.close();
}
}
}
預計回應會回傳一個 json,告知資料是否已插入 de 資料庫中。
uj5u.com熱心網友回復:
歡迎來到 StackOverflow。
首先,您得到的錯誤是error: TimeoutException after 0:00:15.000000: Future not completed.由于您宣告 POST 請求有時會隨機作業,有時我不懷疑后端在某些情況下只需要更多時間來向您發送答案。
要解決此問題,您可以洗掉該.timeout(const Duration(seconds: 15));行。
如果這不能解決它,我會這樣做:
- 嘗試用 Postman 復制問題。如果可以,問題肯定與您的 Flutter 代碼無關。
- 嘗試在 Postman 請求中添加/省略一些標頭。有時標題會導致一些......奇怪的行為。
到目前為止,您的 Flutter 代碼對我來說看起來不錯。如果您知道后端不是罪魁禍首,請更新我們。
uj5u.com熱心網友回復:
在您的場景中,這可能是應用無法隨機接收回應的情況。最好的方法是在找到解決方案之前處理好它。
你的后端需要添加一個條件來服務retries,這是由顫振包http_retry發起的。
當請求失敗時,http_retry 在第一次重試前等待 500ms,每次延遲增加 1.5 倍。
將此包安裝到專案中:
flutter pub add http_retry
使用 http_retry 的解決方案:
Future<void> httpRetries() async {
final client = RetryClient(
http.Client(),
retries: 4,
// change the statusCode with one that can fit your case. When return true, this client will retry once the request
when: (response) =>
response.statusCode != 200 && response.statusCode != 201,
// whenever an error is caught, this client will retry once the request when this function returns true
whenError: (_, stackTrace) {
print(stackTrace);
return true;
},
onRetry: (_, __, ___) => print("retry!"),
);
try {
// use this as usual as a http client
print(await client.post(Uri.parse('https://your-post-url')));
} finally {
client.close();
}
}
uj5u.com熱心網友回復:
我真的很高興你花時間和我一起尋找解決我的問題的方法。我已經和我團隊的后端開發人員談過了,我們發現了問題。
當資料進入 API 時,該程序有一個 UPDATE 集,這個程序花費的時間比我們預期的要多。因此,當更新未完成時,API 會一直凍結,等待更新結論和回應回傳。
有時此更新大約需要 10 秒,有些則超過 2 分鐘。
我們正在尋找此 UPDATE 問題的解決方案。
我非常感謝您的時間。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467989.html
上一篇:如果控制器已初始化(視頻播放器),則顫振dispose()
下一篇:顫振顯示對話框
