【问题标题】:Calling a Cloud Function from Android through Firebase通过 Firebase 从 Android 调用云函数
【发布时间】:2017-08-09 21:49:57
【问题描述】:

情况

我通过functions.https.onRequest 创建了一个谷歌云函数,当我将它的 URL 粘贴到浏览器中并与我的 Firebase 设置很好地集成时,它运行良好。这个函数有点像从后端公开的 API 方法,我想从客户端调用它。在此特定实例中,客户端是一个 Android 应用程序。

问题

有什么方法可以通过 Firebase 调用 Cloud Function 来执行 HTTP 请求?还是我仍需要执行手动 HTTP 请求?

【问题讨论】:

  • 什么意思?使用 Firebase SDK 调用函数?
  • 例如,如果我有一个可在 https://<server>.cloudfunctions.net/newSession 访问的 https 函数,我希望能够调用类似 FirebaseFunctions.getInstance().get("newSession") 的函数,类似于访问其他 Firebase 功能的方式。
  • 我可以建议的是为此功能提交功能请求,因为 AFAIK 还没有适用于 Firebase 功能的独立 SDK。

标签: android firebase google-cloud-functions


【解决方案1】:

从 12.0.0 版本开始,您可以更简单的方式调用云函数

在您的build.gradle 中添加以下行

implementation 'com.google.firebase:firebase-functions:19.0.2'

并使用以下代码

FirebaseFunctions.getInstance() // Optional region: .getInstance("europe-west1")
    .getHttpsCallable("myCoolFunction")
    .call(optionalObject)
    .addOnFailureListener {
        Log.wtf("FF", it) 
    }
    .addOnSuccessListener {
        toast(it.data.toString())
    }

您可以安全地在主线程上使用它。回调也会在主线程上触发。

您可以在官方文档中阅读更多内容:https://firebase.google.com/docs/functions/callable

【讨论】:

  • 如何用这个添加头部授权?
  • @RahulSharma 授权信息由 sdk 自动添加
  • 我们可以将参数传递给这个云函数吗?我们可以只调用云函数还是我们也可以从android代码中创建和添加云函数??
  • @PradeepkumarReddy 参数作为映射传递(参见代码 sn-p 中的 optionalObject),只需确保它们可编码为 JSON。从客户端创建和添加功能?这是可能的,但需要服务帐户 == 巨大的安全漏洞(不知道为什么你希望能够做到这一点)
  • 非常感谢!!我不知道,我还必须提供功能区域客户端!!!!!!
【解决方案2】:

firebaser 在这里

更新:现在有一个客户端 SDK,允许您直接从受支持的设备调用 Cloud Functions。有关示例和最新更新,请参阅 Dima 的答案。

下面的原始答案...


@looptheloop88 是正确的。没有用于从您的 Android 应用调用 Google Cloud Functions 的 SDK。我肯定会file a feature request

但目前这意味着您应该使用从 Android 调用 HTTP 端点的常规方法:

【讨论】:

  • 我们今天可以从 Android 应用调用 Google Cloud Functions 吗?
  • @TheGameChanger 是的。如果您有问题,我建议您使用minimal code that reproduces that problem 创建一个新问题。
  • 你能给我一个链接吗?
  • 我没有问题。我只是想知道我们应该如何从 Android 应用程序调用 Google Cloud Functions?我需要链接、名称或说明?
【解决方案3】:

目前不可能,但正如其他答案中所述,您可以在 Android 中 trigger functions using an HTTP request。如果您这样做,那么使用身份验证机制保护您的函数非常重要。这是一个基本示例:

'use strict';

var functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.helloWorld = functions.https.onRequest((request, response) => {
  console.log('helloWorld called');
  if (!request.headers.authorization) {
      console.error('No Firebase ID token was passed');
      response.status(403).send('Unauthorized');
      return;
  }
  admin.auth().verifyIdToken(request.headers.authorization).then(decodedIdToken => {
    console.log('ID Token correctly decoded', decodedIdToken);
    request.user = decodedIdToken;
    response.send(request.body.name +', Hello from Firebase!');
  }).catch(error => {
    console.error('Error while verifying Firebase ID token:', error);
    response.status(403).send('Unauthorized');
  });
});

要在 Android 中获取令牌,您应该使用 this,然后将其添加到您的请求中,如下所示:

connection = (HttpsURLConnection) url.openConnection();
...
connection.setRequestProperty("Authorization", token);

【讨论】:

    【解决方案4】:

    是的,有可能:

    1. 将此添加到 app/build.gradle 文件:

      实现 'com.google.firebase:firebase-functions:16.1.0'


    1. 初始化客户端 SDK

      私有 FirebaseFunctions mFunctions;

      mFunctions = FirebaseFunctions.getInstance();


    1. 调用函数

      private Task<String> addMessage(String text) {
      
      Map<String, Object> data = new HashMap<>();
      data.put("text", text);
      data.put("push", true);
      
      return mFunctions
              .getHttpsCallable("addMessage")
              .call(data)
              .continueWith(new Continuation<HttpsCallableResult, String>() {
                  @Override
                  public String then(@NonNull Task<HttpsCallableResult> task) throws Exception {
                      // This continuation runs on either success or failure, but if the task
                      // has failed then getResult() will throw an Exception which will be
                      // propagated down.
                      String result = (String) task.getResult().getData();
                      return result;
                  }
              });
         }
      

    Ref : Calling Firebase cloud functions

    【讨论】:

      猜你喜欢
      • 2019-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 2022-11-11
      • 2018-09-29
      • 2021-02-10
      • 2020-05-17
      • 2018-11-18
      相关资源
      最近更新 更多