微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

Flutter - 无法通过 http.get 从 api 获取数据

如何解决Flutter - 无法通过 http.get 从 api 获取数据

我正在尝试从 Unsplash API 获取数据到我的 Flutter 应用程序,但我仍然收到错误 404。为了连接 API,我正在使用 dart:http 包 v.0.13 。我尝试在 Postman 上使用相同的 Uri,但我收到状态代码 200,因此 URL 很好 (https://api.unsplash.com/photos/random/?client_id=API_KEY)。请检查我的代码

Future<void> getRandomImage() async {
var res = await http.get(Uri.https('api.unsplash.com','/photos/random/?client_id=API_KEY'));
if (res.statusCode == 200) {
  var decodedData = jsonDecode(res.body);
  print(decodedData);
} else {
  print(res.statusCode);
  throw 'Problem with the get request';
}}

解决方法

网络服务:

class NetService {
  static Future<T?> getJson<T>(String url,{int okCode = 200}) {
    return http.get(Uri.parse(url))
      .then((response) {
        if (response.statusCode == okCode) {
          return jsonDecode(response.body) as T;
        }
        PrintService.showDataNotOK(response);
        return null;
      })
      .catchError((err) => PrintService.showError(err));
  }
}

主要内容:

import 'dart:async';

import 'package:_samples2/networking.dart';

class Unsplash {
  static const _apiKey = '11111111111111111111111111111';
  static const _url = 'https://api.unsplash.com/photos/random/?client_id=$_apiKey';

  static FutureOr<void> fetchRandomImage() async {
    print('Start fetching...\n');
    await NetService.getJson<Map<String,dynamic>>(_url)
      .then((response) => print(response))
      .whenComplete(() => print('\nFetching done!'));
  }
}

void main(List<String> args) async {
  await Unsplash.fetchRandomImage();
  print('Done!');
}

结果:

Start fetching...

{id: 6qUn2lQF9A4,created_at: 2021-03-06T08:38:48-05:00,updated_at: 2021-03-12T01:39:06-05:00,promoted_at: 2021-03-07T04:56:18-05:00,width: 6000,height: 4000,color: #735959,blur_hash: LJEVHCRk0LWXM_oJt7ozNGWBs:of,description: null,alt_description: woman with blonde hair holding a pen,urls: {raw: https://images.unsplash.com/photo-1615037486765-e96acbe87231?ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1,full: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=srgb&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=85,regular: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=1080,small: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=400,thumb: https://images.unsplash.com/photo-1615037486765-e96acbe87231?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ&ixlib=rb-1.2.1&q=80&w=200},links: {self: https://api.unsplash.com/photos/6qUn2lQF9A4,html: https://unsplash.com/photos/6qUn2lQF9A4,download: https://unsplash.com/photos/6qUn2lQF9A4/download,download_location: https://api.unsplash.com/photos/6qUn2lQF9A4/download?ixid=MnwyMTQ0MjV8MHwxfHJhbmRvbXx8fHx8fHx8fDE2MTU1Njg5NTQ},categories: [],likes: 13,liked_by_user: false,current_user_collections: [],sponsorship: null,user: {id: PZ7vHHbEDBs,updated_at: 2021-03-12T05:45:35-05:00,username: victoriapriessnitz,name: Victoria Priessnitz,first_name: Victoria,last_name: Priessnitz,twitter_username: null,portfolio_url: https://www.instagram.com/victoriapriessnitz_photo/,bio: www.priessnitzstudio.cz
https://www.instagram.com/priessnitzstudio/,location: Czech Republic,links: {self: https://api.unsplash.com/users/victoriapriessnitz,html: https://unsplash.com/@victoriapriessnitz,photos: https://api.unsplash.com/users/victoriapriessnitz/photos,likes: https://api.unsplash.com/users/victoriapriessnitz/likes,portfolio: https://api.unsplash.com/users/victoriapriessnitz/portfolio,following: https://api.unsplash.com/users/victoriapriessnitz/following,followers: https://api.unsplash.com/users/victoriapriessnitz/followers},profile_image: {small: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=32&w=32,medium: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=64&w=64,large: https://images.unsplash.com/profile-1588431995209-edb1b4743462image?ixlib=rb-1.2.1&q=80&fm=jpg&crop=faces&cs=tinysrgb&fit=crop&h=128&w=128},instagram_username:  victoriapriessnitz_photography,total_collections: 0,total_likes: 4,total_photos: 266,accepted_tos: true,for_hire: false},exif: {make: null,model: null,exposure_time: null,aperture: null,focal_length: null,iso: null},location: {title: null,name: null,city: null,country: null,position: {latitude: null,longitude: null}},views: 91851,downloads: 939}

Fetching done!
Done!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。