调用http获取url,其中包含有空格的数据



当我调用这个函数时,如果艺术家和专辑有没有空格的数据,它就会工作。我该如何改变它,使它考虑带有空格的数据呢?

static Future fetchAlbumDetailData(String albumName, String artist) async {
print('ALBUM NAME : $albumName');
print('ALBUM artist : $artist');
print(
'Link called is :https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=$apiKey&artist=$artist&album=$albumName&format=json');
http.Response response = await retry(
// Make a GET request
() => http
.get(
Uri.parse(
'https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=$apiKey&artist=$artist&album=$albumName&format=json'),
)
.timeout(const Duration(seconds: 5)),
// Retry on SocketException or TimeoutException
retryIf: (e) => e is SocketException || e is TimeoutException,
);
if (response.statusCode == 200) {
return response.body;
} else {
throw (response.statusCode);
}
}

我的print语句输出是:

I/flutter (5341): ALBUM NAME: Make Believe I/flutter (5341): ALBUM艺术家:Weezer I/flutter(5341):链接叫做is: https://ws.audioscrobbler.com/2.0/?method=album.getinfo& api_key = 755 bf5e882b716dac814852b5e8e2e52&艺术家= Weezer&专辑=Believe&格式= json

Make和Believe之间的链接被破坏

Uri类提供encodeFullencodeComponentencodeQueryComponent方法来转义为其他目的为uri保留的字符。

在您的情况下,因为您的字符串将是查询字符串的一部分,您应该使用Uri.encodeQueryComponent。请注意,这将空格编码为+而不是%20,但+对于查询字符串组件更正确。(参见:URL编码空格字符:+或%20?)

您实际上不需要替换String,因为Uri.parse将您的空格变为%20

在这里我测试了这个简单的应用程序,似乎通话工作正常。

至于您的null check operator error,当您在一个值上使用感叹号符号!来强制它为非空时,它通常会发生,但它实际上是空的。如果你能分享更多你的代码(与null安全相关的部分),这样我们就能进一步支持。

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
final uri =
'https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=755bf5e882b716dac814852b5e8e2e52&artist=Weezer&album=Make Believe&format=json';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Sample App'),
),
body: Container(
child: Center(
child: TextButton(
child: Text('Press me'),
onPressed: () => fetchAlbumDetailData(uri),
),
)),
),
);
}
static Future fetchAlbumDetailData(_uri) async {
print(Uri.parse(_uri));
// Print out: https://ws.audioscrobbler.com/2.0/?method=album.getinfo&api_key=755bf5e882b716dac814852b5e8e2e52&artist=Weezer&album=Make%20Believe&format=json
final result = await http
.get(Uri.parse(_uri))
.timeout(const Duration(seconds: 5));
print(result.body);
}
}

在调用get之前请将空格替换为%20。像这样。albumName.replaceAll(";","% 20")

最新更新