user3557972
user3557972

Reputation: 35

How use HttpClient class to request multiple URLs without losing the relation between the URL

I would like to request some URLs and combine the result with the requested data.

For example I would like to call https://postman-echo.com/time/leap to find out if a year is a leap. For this I have to use the parameter timestamp like: https://postman-echo.com/time/leap?timestamp=2016-01-01 which returns true.

In this case I have data "2016-01-01" and the result "true". After combining both I have:

{2016-01-01: true}

To check multiple dates I would like to call the URL multiple times and get the result like :

{2015-01-01: false}
{2016-01-01: true}
{2017-01-01: false}

But my implementation failed to combine the data value and I can't figure out why. I get the result

{2016-01-01: false}
{2017-01-01: false}
{2015-01-01: false}

Here the the code, I tried to solve my Problem. https://dartpad.dartlang.org/78049ae322d87cb73588e8cec28d0bdf

Upvotes: 1

Views: 909

Answers (1)

Maximilian Riegler
Maximilian Riegler

Reputation: 23506

This looks like a race condition, _url and _responseBody probably shouldn't be member variables.

I'd make _url a local variable and _sendRequest could actually return the responseBody:

Future<Map<String, List>> sendRequestForLeapyear(String year) async {
  var url = "${_address}/time/leap?timestamp=${year}";
  var responseBody = await _sendRequest(url);
  var responseMap = JSON.decode(responseBody);
  var isLeap = responseMap['leap'];
  return {year : isLeap};
}

Future<String> _sendRequest(String url) async {
  HttpClient client = new HttpClient();
  return await client.getUrl(Uri.parse(url)).then((HttpClientRequest request) {
    request.persistentConnection = false;
    return request.close();
  }).then((HttpClientResponse response) {
    return response.transform(UTF8.decoder).join("").then((String body) {
      return body;
    });
  }).catchError((e) {
    throw new StateError("failed to poll $_url because: $e");
  }).whenComplete(client.close);
}

Edit: also you misspelled the API endpoint's parameter timestamp :D

Upvotes: 2

Related Questions