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

Posted

技术标签:

【中文标题】Flutter - 无法通过 http.get 从 api 获取数据【英文标题】:Flutter - not able to fetch data from api via http.get 【发布时间】:2021-06-10 16:43:15 【问题描述】:

我正在尝试从 Unsplash API 获取数据到我的 Flutter 应用程序,但我仍然收到错误 404。要连接 API,我正在使用 dart:http package 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';

【问题讨论】:

【参考方案1】:

网络服务:

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!

【讨论】:

以上是关于Flutter - 无法通过 http.get 从 api 获取数据的主要内容,如果未能解决你的问题,请参考以下文章

如何从flutter应用程序向本地主机发出http get请求?

Flutter:在 http.get 请求之后构建 ListView

Flutter:为 Http GET 请求发送 JSON 正文

我无法将 URL 链接分配给 http.get() [重复]

flutter http get请求

Flutter - http.get 在 macos 构建目标上失败:连接失败