问号在URI中转换为%3F

时间:2019-11-02 16:23:25

标签: flutter dart

我正在从事一个项目,并且试图从API获取信息。当我编写链接时,它不会检测到字符“?”并将此字符替换为“%3F”,因此我无法访问API。

final String _charactersUrl = '/api/character/?page=2';

我从API获取状态代码500:

https://rickandmortyapi.com/api/character/%3Fpage=3

从API获取信息的类

class Api {

  final String _baseUrl = 'rickandmortyapi.com';
  final String _charactersUrl = '/api/character/?page=2';
  final String _charactersJsonKey = 'results';

  final HttpClient _httpClient = HttpClient();

  Future<List<Character>> getCharacters() async {
    final uri = Uri.https(_baseUrl, _charactersUrl);
    final response = await _getJson(uri);

    if (response == null || response[_charactersJsonKey] == null) {
      print('Api.getCharacters(): Error while retrieving characters');
      return null;
    }

    return _convert(response[_charactersJsonKey]);
  }

  Future<Map<String, dynamic>> _getJson(Uri uri) async {
    try {
      final request = await _httpClient.getUrl(uri);
      final response = await request.close();

      if (response.statusCode != HttpStatus.OK) {
        print('Api._getJson($uri) status code is ${response.statusCode}');
        return null;
      }

      final responseBody = await response.transform(utf8.decoder).join();
      return json.decode(responseBody);
    } on Exception catch (e) {
      print('Api._getJson($uri) exception thrown: $e');
      return null;
    }
  }

  List<Character> _convert(List charactersJson) {
    List<Character> characters = <Character>[];

    charactersJson.forEach((character) {
      characters.add(Character.fromJson(character));
    });

    return characters;
  }
}

如果有人可以帮助我,我将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

Uri类希望您以不同的方式使用Uri.https constructor

第三个位置参数是queryParameters,而不是将查询参数传递到unencodedPath

final String _baseUrl = 'rickandmortyapi.com';
final String _charactersPath = '/api/character/';
final Map<String, String> _queryParameters = <String, String>{
  'page': '2',
};

Future<List<Character>> getCharacters() async {
    final uri = Uri.https(_baseUrl, _charactersPath, _queryParameters);
    ...