使用标准库将字符串转换为 DART 中的 GET 请求参数



我有一个多字字符串,我想将其转换为GET请求参数。

我有一个 API 端点/search,它接受参数 query .现在,通常您的请求看起来像http://host/search?query=Hello+World .

我有一个String Hello World,我想将其转换为此 URL 编码参数。

当然,我可以编写逻辑以将其分解为单词并在两者之间添加一个+,但我想知道 URI 类是否可以帮助解决这个问题

我正在使用Dart的httpClient来提出请求。

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 "{}";
  }
}

本质上,需要将queryToSearch编码为 URL 参数。

您可以使用

将所有内容(查询、主机和路径(包装在一起并相应地对其进行编码的Uri.http(s)

    final uri = new Uri.http(config['API_ENDPOINT'], '/search', {"query": queryToSearch});

Uri 类为此提供了方法

  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeQueryComponent.html
  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeFull.html
  • https://api.dartlang.org/stable/1.24.3/dart-core/Uri/encodeComponent.html

如果您以这种方式拥有完整的 URL,则可以使用 Uri.parse(url_string)

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

最新更新