Android应用调用“仅自己访问”的Apps Script获取谷歌表格数据失败求助
解决Android调用仅限自身访问的Google Apps Script问题
核心原因
当Apps Script部署设置为「Who has access: Only Myself」时,普通HTTP请求无法通过身份验证——即使模拟器登录了对应Google账号,Volley的GET请求也不会自动携带身份凭证,必须通过OAuth2授权传递有效令牌。
具体解决步骤
1. 关联Apps Script到自定义Google Cloud Platform (GCP)项目
- 打开目标Apps Script,点击右上角「设置」,勾选显示appsscript.json清单文件
- 打开
appsscript.json,确保oauthScopes包含以下权限(根据需求调整):"oauthScopes": [ "https://www.googleapis.com/auth/spreadsheets.readonly", "https://www.googleapis.com/auth/script.external_request" ] - 返回「项目设置」,找到「Google Cloud Platform (GCP) 项目」,点击「更改项目」,选择你自己创建的GCP项目(无则新建)
2. 在GCP中配置OAuth2凭据
- 进入GCP控制台,导航到「API和服务」→「OAuth同意屏幕」,选择内部类型(仅限自身使用),完成基础信息填写并添加上述OAuth范围
- 进入「凭据」→「创建凭据」→「OAuth客户端ID」,应用类型选Android,填写你的Android应用的包名和SHA-1指纹(可从Android Studio的「Gradle」→「Tasks」→「android」→「signingReport」获取)
3. 修改Android端代码,添加OAuth2授权头
- 首先在Module级
build.gradle中添加Google Sign-In依赖:implementation 'com.google.android.gms:play-services-auth:20.7.0' - 实现Google登录流程,获取有效访问令牌后,在Volley请求中添加Authorization头:
// 假设已完成Google登录,获取到已登录账号 GoogleSignInAccount account = GoogleSignIn.getLastSignedInAccount(this); String accessToken = account.getIdToken(); StringRequest stringRequest = new StringRequest(Request.Method.GET, SCRIPT_URL, response -> Log.i("response", response), error -> Log.e("request_error", error.getMessage()) ) { @Override public Map<String, String> getHeaders() throws AuthFailureError { HashMap<String, String> headers = new HashMap<>(); headers.put("Authorization", "Bearer " + accessToken); return headers; } }; // 将请求加入Volley请求队列 RequestQueue queue = Volley.newRequestQueue(this); queue.add(stringRequest);
4. 验证部署与权限
- 确认Apps Script部署设置为:
- Execute as: Me
- Who has access: Only Myself
- 确保Android模拟器登录的Google账号与Apps Script部署者账号完全一致
注意事项
- 若使用
getServerAuthCode,需额外向Google OAuth服务器兑换为有效Access Token(推荐直接使用getIdToken简化流程) - GCP中配置的包名和SHA-1必须与Android应用完全匹配,否则会触发授权失败
- 测试阶段可在OAuth同意屏幕添加测试用户(即使是内部应用)
内容的提问来源于stack exchange,提问作者Christine Tang
相关产品推荐
相关产品推荐

