我正在阅读 Simone Alessandria 撰写的《Flutter Cookbook - 第二版》第 8 章,我注意到
getData
方法有一个无效的 URL http://google.com/books/v1/volumes/junbDwAAQBAJ
。我不知道如何修改 URL 以从 API 获取结果。
这是代码:
Future<Response> getData() async {
const authority = 'www.googleapis.com';
const path = '/books/v1/volumes/junbDwAAQBAJ';
Uri url = Uri.https(authority, path);
return http.get(url);
}
完整代码可以在作者的GitHub
找到URL 有效并具有 JSON 响应:
https://www.googleapis.com/books/v1/volumes/junbDwAAQBAJ
以下是调用的方式:
void getData() async{
String url = 'https://www.googleapis.com/books/v1/volumes/junbDwAAQBAJ';
try{
var response = await http.get(Uri.parse(url));
if(response.statusCode == 200){
print('Done: \n ${response.body}');
}
}
catch(e){
print('Something went wrong');
}
}