I'm not receiving response from API when making a post requisition in FLUTTER

253

Solution 1

Welcome to StackOverflow.

First of all the error you get is error: TimeoutException after 0:00:15.000000: Future not completed. Since you state that the POST request sometimes randomly works and sometimes doesn't I suspect that the backend in some cases just requires more time to send you an answer.

To fix this you can remove the .timeout(const Duration(seconds: 15)); line.

If this does not fix it I would do this:

  1. Try to replicate the problem with Postman. If you can the problem is definitely not related to your Flutter code.
  2. Try to add/leave out some headers in the Postman request. Sometimes headers cause some ... weird behaviour.

As of now your Flutter code looks good to me. If you know that the backend is not to blame please update us.

Solution 2

In your scenario, this may be a case the app cannot receive response randomly. The best way is to handle it well before you find a solution.

Your backend needs to add a condition to serve on retries, which is initiated by flutter package http_retry.

When an request fails, http_retry waits 500ms before the first retry, and increases the delay by 1.5x each time.

Install this package to the project:

flutter pub add http_retry

Solution with 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();
  }
}
Share:
253
WesleyAlmont
Author by

WesleyAlmont

Updated on January 04, 2023

Comments

  • WesleyAlmont
    WesleyAlmont over 1 year

    I'm facing a strange error when I'm sending data to an API.

    I have some endpoints that work pretty fine when I send and receive data. But one of those is giving me some trouble.

    I'll try to explain.

    So when I send a data object through the POST method using the HTTP package, the data which was sent is reaching the database and is added, but nothing is coming back from requisition.

    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();
        }
        }
      }
    

    it is expected that the response returns a json informing whether the data was inserted or not in de database.

    • mondayrris
      mondayrris almost 2 years
      Is this method an exceptionally a POST request method while others API methods worked functionally are in GET request method?
    • Sarthak Bansal
      Sarthak Bansal almost 2 years
      are you able print response status code? Can you try to run outside the try and see the response?
    • WesleyAlmont
      WesleyAlmont almost 2 years
      @mondayrris I've got some POST methods, GET request is working fine. Only this endpoint is not working as expeted.
    • WesleyAlmont
      WesleyAlmont almost 2 years
      @SarthakBansal I'm having this error: TimeoutException after 0:00:15.000000: Future not completed. I increased the time of timeException but still happens at different times.
    • mondayrris
      mondayrris almost 2 years
      When there is Future not completed, I suspect that the backend code failed to comply within short period of time. Refine the backend code if possible. To fast test the responsibility to rely on either Flutter and backend, if you are also the backend developer, return a valid initial json (a mock case) without doing anything other than this.
    • WesleyAlmont
      WesleyAlmont almost 2 years
      @mondayrris When i start the services of API for the first time of the day it works well. I've been sending some json sales to this EP but after 5 or more calls it stops to work and the error mentioned above is are displayed. I don't really know why this behavior are happening. Sometimes work and sometimes not.
    • mondayrris
      mondayrris almost 2 years
      In backend scope, does any events being hooked within the process of execution (json sales received and saved) and dispatched after this before the end of execution, such as notify users by email, generate invoice and receipt?
    • WesleyAlmont
      WesleyAlmont almost 2 years
      Actually, my process is working in that way: 1 - First Call another EP with POST method and get the response to compose sales json. (at this point my code works fine) 2 - After-sales json is completely formed I'll try to send it to the EP api/v1/carga_venda 3- sometimes this EP returns a response from the calling, when works I get this response and display a flushMessage, informing that sales were completely sent and inserted into the database and finally moves to another screen which gives some pieces of information as well as Sales ID, option to send the sales coupon by email.
    • WesleyAlmont
      WesleyAlmont almost 2 years
      But in the backend which we are using fastAPI (python) is working very very well in our desktop application and web application, all of one is under development but ONLY in the Android application, these errors are occurring.
  • WesleyAlmont
    WesleyAlmont almost 2 years
    Okay, i'll try to replicate this behavior following your tips.
  • mondayrris
    mondayrris almost 2 years
    Never mind. Take your time :)
  • WesleyAlmont
    WesleyAlmont almost 2 years
    I'm really happy with the time you spent with me to find a solution to my problem. I've spoken iwth backend developer from my team and we found the problem. When the data comes into the API the process has an UPDATE set, this process is taking more time than we expected. So while the update is not finished the API keeps freezed waiting that update conclusions and response comes back. Sometimes this update is taking about 10s and some more than 2min. We are looking for a solution to this UPDATE problem. I am very grateful for your time.