如果Flutter中没有响应,重试Http Get请求

l3zydbqr  于 2023-05-19  发布在  Flutter
关注(0)|答案(4)|浏览(213)
getData() async {
    http.Response response = await http.get('https://www.example.com/);
    print(response.body);
}

上面的函数用于获取页面的HTML代码,但在某些情况下会失败。该功能有时永远不会完成,它永远等待得到响应(例如,如果应用程序是打开的,而互联网是关闭的,即使当它打开,它永远不会连接)。在这种情况下,有没有什么方法可以重新尝试?
我尝试了HTTP重试包,但它给了我15+错误。

luaexgnf

luaexgnf1#

示例代码说明如何做到这一点:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<List> loadData() async {
  bool loadRemoteDatatSucceed = false;
  var data;
  try {
    http.Response response = await http.post("https://www.example.com",
        body: <String, String>{"username": "test"});
    data = json.decode(response.body);
    if (data.containsKey("success")) {
      loadRemoteDatatSucceed = true;
    }
  } catch (e) {
    if (loadRemoteDatatSucceed == false) retryFuture(loadData, 2000);
  }
  return data;
}

retryFuture(future, delay) {
  Future.delayed(Duration(milliseconds: delay), () {
    future();
  });
}
ugmeyewa

ugmeyewa2#

您可以使用http包中的RetryPolicy来重试连接,只需创建自己的类并继承RetryPolicy并覆盖这些函数,如以下示例,然后使用www.example.com创建一个ClientHttpClientWithInterceptor.build并添加您的自定义retryPolicy作为参数,这将重试您的请求多次,直到满足条件,如果不满足,它将停止重试。

import 'package:http/http.dart';

class MyRetryPolicy extends RetryPolicy {
  final url = 'https://www.example.com/';

  @override
  // how many times you want to retry your request.
  int maxRetryAttempts = 5;

  @override
  Future<bool> shouldAttemptRetryOnResponse(ResponseData response) async {
    //You can check if you got your response after certain timeout,
    //or if you want to retry your request based on the status code,
    //usually this is used for refreshing your expired token but you can check for what ever you want

    //your should write a condition here so it won't execute this code on every request
    //for example if(response == null) 

    // a very basic solution is that you can check
    // for internet connection, for example
    try {
      final result = await InternetAddress.lookup('google.com');
      if (result.isNotEmpty && result[0].rawAddress.isNotEmpty) {
        return true;
      }
      return false;
    } on SocketException catch (_) {
      return false;
    }
  }
}

然后创建并使用客户端来发出请求。
如果满足您写入的条件,它将自动重试请求。

Client client = HttpClientWithInterceptor.build(
        retryPolicy: ExpiredTokenRetryPolicy(),
      );

final response = await client.get('https://www.example.com/);

还有一个软件包来检查互联网连接,如果你的问题,请参阅connectivity

txu3uszq

txu3uszq3#

你可以像在同步代码中一样在异步函数中使用try-catch块。也许您可以在函数中添加某种错误处理机制,并在出现错误时重试该函数?这里有一些关于这个的文件。
文档示例:

try {
    var order = await getUserOrder();
    print('Awaiting user order...');
  } catch (err) {
    print('Caught error: $err');
  }

您还可以按照this github issue.捕获特定的异常

doLogin(String username, String password) async {
    try {
     var user = await api.login(username, password);
      _view.onLoginSuccess(user);
    } on Exception catch(error) {
      _view.onLoginError(error.toString());
    }
  }

编辑:这可能也有帮助。
当我们在这方面的时候,看看here有一个函数,它可以尝试异步操作,无论你需要多少次。

1zmg4dgp

1zmg4dgp4#

您可以捕获异常并根据需要继续重试。
下面是一个函数:

get(url, {count = 0}) async {
  try {
    var response = await http.get(
      Uri.parse(url),
    );
    return response.body;
  } catch (error) {
    if (count < 8) {
      print('count is ' + count.toString());
      count += 1;
      return await Future.delayed(Duration(milliseconds: 2000), () async {
        return await get(url, count: count);
      });
    } else {
      print('failed');
    }
  }
}

相关问题