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

如何将Google Cloud Vision接入Flutter应用?解决403错误

问题描述

我希望将Google Cloud Vision接入我的Flutter应用,以下是我的代码:

import 'package:dio/dio.dart';

const _apiPREFIX = "https://vision.googleapis.com";


class Server {
  Future<void> postReq() async {
    Response response;
    Dio dio = Dio();
    Map<String, dynamic> data = {
      "requests": [
        {
          "image": {
            "source": {
              "imageUri":
                  "https://image.msscdn.net/images/goods_img/20200729/1530505/1530505_2_500.jpg?t=20210902101946"
            }
          },
          "features": [
            {"type": "LABEL_DETECTION", "maxResults": 1}
          ]
        }
      ]
    };
    try {
      response = await dio.post(
        "$_apiPREFIX/v1/images:asyncBatchAnnotate?key=(my api key)",data: data
      );
      print(response.data.toString());
    } catch (e) {
      print(e);
    }

  }
}

Server server = Server();

我已拥有Google API Key,但不清楚如何正确使用它,调用接口时收到403错误,请问该如何解决此问题?

解决方法

1. 修正API接口路径

你当前调用的asyncBatchAnnotate是异步批量标注接口,要求配合Google Cloud Storage使用,权限配置复杂,不适合客户端直接调用。应该改用同步单图标注接口annotate,路径修改为:

"$_apiPREFIX/v1/images:annotate?key=你的实际API_KEY"

2. 检查API Key的权限与配置

  • 登录Google Cloud控制台,确认你的API Key已开启Cloud Vision API服务;
  • 查看API Key的限制设置:如果是移动端Flutter应用,不要设置IP限制,可选择设置应用签名验证(Android)或Bundle ID验证(iOS);Web端可设置HTTP referrer限制;
  • 确认项目的Cloud Vision API配额未超限。

3. 验证请求参数有效性

确保imageUri指向的图片是公网可访问的,没有防盗链或权限限制,Google服务器需要能正常拉取到该图片。

4. 可选:通过请求头携带API Key

除了URL参数,也可以通过请求头传递API Key,写法如下:

Dio dio = Dio();
dio.options.headers['X-Goog-Api-Key'] = "你的实际API_KEY";

// 请求时URL无需携带key参数
response = await dio.post("$_apiPREFIX/v1/images:annotate", data: data);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 12:10:27