Flutter调用带空格参数的HTTP GET请求时URL断裂如何修复
问题根因
你当前手动拼接URL查询参数,没有对参数做URL编码处理,空格属于URL中的非法字符,会直接截断URL结构,导致请求路径异常。
修复方案
推荐使用Dart Uri类自带的构造方法传入queryParameters,框架会自动对所有参数做标准URL编码,不需要手动处理特殊字符,稳定性更高。
修改后的完整代码如下:
static Future fetchAlbumDetailData(String albumName, String artist) async { print('ALBUM NAME : $albumName'); print('ALBUM artist : $artist'); // 用Uri构造方法自动处理参数编码 final requestUri = Uri.https( 'ws.audioscrobbler.com', '/2.0/', { 'method': 'album.getinfo', 'api_key': apiKey, 'artist': artist, 'album': albumName, 'format': 'json' }, ); print('Link called is :$requestUri'); http.Response response = await retry( () => http .get(requestUri) .timeout(const Duration(seconds: 5)), retryIf: (e) => e is SocketException || e is TimeoutException, ); if (response.statusCode == 200) { return response.body; } else { throw (response.statusCode); } }
如果确实需要手动拼接URL,可以用Uri.encodeComponent()方法对每个参数单独编码:
// 手动编码示例 final encodedAlbumName = Uri.encodeComponent(albumName); final encodedArtist = Uri.encodeComponent(artist); final url = 'https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=$apiKey&artist=$encodedArtist&album=$encodedAlbumName&format=json';
这种方式更灵活但容易遗漏编码步骤,更推荐使用queryParameters的自动处理方案。
内容的提问来源于stack exchange,提问作者Anish Hemachandran
相关产品推荐
相关产品推荐

