首页 > 解决方案 > How to avoid Uri encoding using Uri.https from Dart library

问题描述

I've this snippet to access a rest service. But the method Uri.https are undesirable encoding the url resulting in:

https://unogs-unogs-v1.p.mashape.com/aaapi.cgi?query=new%3A7-%211900%2C2018-%210%2C5-%210%2C10-%210-%21Any-%21Any-%21Any-%21gt100-%21Yes&type=ns&st=adv&orderBy=Relevance&andOr=and

I want to let Url as is: 'new:7-!1900,2018-!0,5-!0,10-!0-!Any-!Any-!Any-!gt100-!Yes'

In Retrofit/Kotlin I simply put encoded=false to Query parameter: @Query("q", encoded = true)

import 'dart:async';
import 'package:http/http.dart' as http;

class FetchMovies {
  final queryParameters = {
    'query': 'new:7-!1900,2018-!0,5-!0,10-!0-!Any-!Any-!Any-!gt100-!Yes',
    'type': 'ns',
    'st': 'adv',
    'orderBy': "Relevance",
    'andOr': 'and'
  };

  Future<http.Response> execute() async {
    var uri = Uri.https(
        'unogs-unogs-v1.p.mashape.com', '/aaapi.cgi', queryParameters, );
    print(uri.toString());


    return await http.get(uri, headers: {
      'X-Mashape-Key': '',
      'Accept': 'application/json'
    });

  }
}

标签: httpdart

解决方案


即使添加查询部分也unencodedPath可以解决问题,这样我就必须摆脱queryParameters并且必须以动态方式构建查询字符串。我发现的最佳解决方案是使用decodeComponentUri 类的实用方法:

return await http.get(Uri.decodeComponent(uri.toString()), headers: {
  'X-Mashape-Key': '',
  'Accept': 'application/json'
});

推荐阅读