Convert String to GET request Parameter in Dart using standard library
Asked Answered
C

3

8

I have a multiword String that I'd like to convert to a GET request parameter.

I have an API endpoint /search that takes in the parameter query. Now typically your request would look like http://host/search?query=Hello+World.

I have a String Hello World that I'd like to convert to this URL encoded parameter.

Ofcourse, I could just write the logic to break it into words and add a + in between but I was wondering if the URI class could help with this

I'm using Dart's httpClient to make a request.

Future<String> _getJsonData(String queryToSearch) async {
  List data = new List();
  var httpClient = new HttpClient();

  var request = await httpClient.getUrl(Uri.parse(
      config['API_ENDPOINT'] + '/search?query=' +
          queryToSearch));

  var response = await request.close();
  if (response.statusCode == HttpStatus.OK) {
    var jsonString = await response.transform(utf8.decoder).join();
    data = json.decode(jsonString);
    print(data[0]);
    return data[0].toString();
  } else {
    return "{}";
  }
}

Essentially, need to encode queryToSearch as the URL parameter.

Clementina answered 18/4, 2018 at 11:58 Comment(0)
H
13

You can use Uri.http(s) which wrap everythings (query, host, and path) together and encode them accordingly.

    final uri = new Uri.http(config['API_ENDPOINT'], '/search', {"query": queryToSearch});
Haplite answered 18/4, 2018 at 12:3 Comment(1)
Just what I needed. I was trying Uri.ecode but that's for encoding the POST body. The documentation wasn't very explicit about passing queries like this in GET requestsClementina
L
2

You can use Uri.parse(url_string) if you have the full URL in this way.

final String accountEndPoint = 'https://api.npoint.io/2e4ef87d9ewqf01e481e';

Future<Account> getAccountData() async {
    try {
      final uri = Uri.parse(accountEndPoint); // <===
      final response = await http.get(uri);
      if (response.statusCode == 200) {
        Map<String, dynamic> accountJson = jsonDecode(response.body);
        return Future.value(Account.fromJson(accountJson));
      } else {
        throw Exception('Failed to get account');
      }
    } catch (e) {
      return Future.error(e);
    }
  }

Looseleaf answered 16/4, 2021 at 16:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.