flutter:HTTP获取请求-禁用编码参数

时间:2019-10-10 08:26:11

标签: http flutter encoding get

我正在尝试制作一个带有波动的演示应用程序,并尝试从magento演示站点获取产品。 这是我的代码:

Future<List<Product>> fetchProducts() async {
  final params = <String, String>{
    'searchCriteria[filter_groups][0][filters][0][condition_type]': 'in',
    'searchCriteria[filter_groups][0][filters][0][field]': 'type_id',
    'searchCriteria[pageSize]': '20',
    'searchCriteria[filter_groups][0][filters][0][value]': 'simple,configurable,bundle',
    'searchCriteria[currentPage]': '1',
    'searchCriteria[sortOrders][0][field]': 'created_at',
    'searchCriteria[sortOrders][0][direction]': 'DESC'
  };
  var uri = Uri.parse('https://demo.com/rest/v1/default/products');
  uri = uri.replace(queryParameters: params);
  print(uri);


  final response =
  await http.get(uri, headers: {HttpHeaders.authorizationHeader: "Bearer qb7157owxy8a29ewgogroa6puwoafxxx"});

  if (response.statusCode == 200) {
    // If the call to the server was successful, parse the JSON.
    final data = json.decode(response.body);
    final products = data["items"] as List;
    return products.map<Product>((json) => Product.fromJson(json)).toList();
  } else {
    // If that call was not successful, throw an error.
    throw Exception('Failed to load post');
  }
}

当我调试时,响应为400-错误的请求。我猜这是因为uri被编码为包含如下所示的百分比字符: enter image description here

那么如何禁用uri编码? 谢谢你们。

1 个答案:

答案 0 :(得分:0)

我相信您应该替换:

  var uri = Uri.parse('https://demo.com/rest/v1/default/products');
  uri = uri.replace(queryParameters: params);
  print(uri);

具有:

  var uri = Uri.https('demo.com', '/rest/v1/default/products', params);

有关此的更多信息:Uri.https

更多信息:replace

示例结果:

enter image description here

无论如何,如果我尝试使用您的参数,该库将表现正常并编码特殊字符。 (see more here

如果我们将实际请求放入浏览器中以检查响应,则:

https://demo.mage-mobile.com/rest/v1/default/products?searchCriteria[filter_groups][0][filters][0][condition_type]=in&searchCriteria[filter_groups][0][filters][0][field]=type_id&searchCriteria[pageSize]=20&searchCriteria[filter_groups][0][filters][0][value]=simple%2Cconfigurable%2Cbundle&searchCriteria[currentPage]=1&searchCriteria[sortOrders][0][field]=created_at&searchCriteria[sortOrders][0][direction]=DESC

我们收到以下答复:

enter image description here

这使我感到最初的怀疑:该API不支持此调用。

也许您还应该从代码中检查这种类型的参数:'searchCriteria [filter_groups] [0] [filters] [0] [condition_type]',看来您正在尝试访问一些来自集合的信息,但实际上是写一个字符串... 尝试从这些参数id中删除引号('bla bla')...也尝试将请求直接放在浏览器(或邮递员)中以查看其工作。

关于编码(将 [更改为%5B )-这是正常现象,应该会发生。