You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter Get API调用异常求助:无法获取图片URL且无预期输出

Flutter调用Get API获取图片URL失败排查与修复

我在Flutter中调用Get API获取图片URL时遇到问题,尝试了两种实现方法均未成功。我认为即使API链接有误,终端也应至少输出JSON文本,且最终需正常展示图片。

尝试过的代码

第一段代码

Future<dynamic> getPhotoUrl(int profileID) async {
    print("get Photo url $profileID");
    var client = http.Client();
    var url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
    Map<String, String> headers = {
      'APIVersion': '1',
      "Authorization": token,
    };

    var response = await client.get(url, headers: headers);
    if (200 == response.statusCode) {
      return response.body;
    } else {

    }
    print("avatar url: $currentPhotoUrl");
  }

第二段代码

Future<void> getPhotoUrl(int profileID) async {
    print("get photo url $profileID");
    var client = http.Client();

    Map<String, String> headers = {
      "Authorization": token
    };
    final http.Response response = await client.get(
        Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos"),
        headers: headers);

    if (response.statusCode == 200) {
      Map responseBody = jsonDecode(response.body);
      var data = responseBody["data"];
      if (data.length < 1) {}
      else {
        currentPhotoUrl.value = data[0]["content"][0]["medium"];
      }
    } else {
      throw WebSocketException("server error: ${response.statusCode}");
    }

    print("photos url: $currentPhotoUrl");
  }

现有代码问题分析

  • 第一段代码:

    • 非200状态码分支无任何处理,无法排查请求失败原因
    • 成功分支直接return,末尾的print永远不会执行
    • 未解析JSON响应,无法提取有效图片URL
  • 第二段代码:

    • 错误处理误用WebSocketException(这是HTTP请求,应使用通用Exception)
    • 空数据分支无逻辑,未设置默认图片
    • 未打印非200状态码的响应体,无法得知服务器返回的错误详情

修复后的实现方案

import 'dart:convert';
import 'package:http/http.dart' as http;

Future<String?> getPhotoUrl(int profileID) async {
  print("get photo url $profileID");
  final client = http.Client();
  final url = Uri.parse("$profileBaseUrl/api/v2/profiles/$profileID/photos");
  final headers = {
    'APIVersion': '1',
    "Authorization": token,
  };

  try {
    final response = await client.get(url, headers: headers);
    // 强制打印所有响应信息,彻底解决无JSON输出的问题
    print("API状态码: ${response.statusCode}");
    print("API响应体: ${response.body}");

    if (response.statusCode == 200) {
      final responseBody = jsonDecode(response.body) as Map<String, dynamic>;
      final data = responseBody["data"] as List?;
      
      if (data != null && data.isNotEmpty) {
        final content = data[0]["content"] as List?;
        if (content != null && content.isNotEmpty) {
          final mediumUrl = content[0]["medium"] as String?;
          if (mediumUrl != null) {
            currentPhotoUrl.value = mediumUrl;
            return mediumUrl;
          }
        }
      }
      // 无有效图片时设置默认URL
      currentPhotoUrl.value = "https://your-default-image-url.com";
      return currentPhotoUrl.value;
    } else {
      throw Exception("请求失败: 状态码${response.statusCode},响应: ${response.body}");
    }
  } catch (e) {
    print("请求异常: $e");
    // 异常时也设置默认图片,保证UI正常显示
    currentPhotoUrl.value = "https://your-default-image-url.com";
    return null;
  } finally {
    client.close(); // 确保释放资源
  }
}

关键优化点

  1. 全链路日志:无论请求成败都打印状态码和响应体,直接解决看不到JSON输出的问题
  2. 空安全防护:逐层校验JSON字段,避免空指针崩溃
  3. 完善错误处理:捕获网络、解析等所有异常,同时设置默认图片保证UI不崩溃
  4. 资源管理:用finally关闭HTTP客户端,避免资源泄漏
  5. 还原请求头:补全APIVersion头,避免因API版本/权限不匹配导致的请求失败

内容的提问来源于stack exchange,提问作者TheBedanse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:15:35