通过 android 改造访问 https 云功能端点

access https cloud function end point via android retrofit

我正在尝试从云功能中获得响应,使用 Android 中的改造。

不知道有没有必要提一下,不过在functions/index.js里面除了下图还有其他功能

以下是我编写云函数端点的方式:

const functions = require('firebase-functions');
const express = require('express');
const app = express();

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

app.post('/shipping', (req, res) => {
  console.log('Inside https request for shipping')
  res.status(200).send('Helo from express post');
})

exports.shipping = functions.https.onRequest(app);

下面是我如何从 Android 调用终点:

FirebaseApi

public interface FirebaseApi {
    @POST("shipping")
    Call<String> getShippingPrice();
}

请求:

private void sendRequestToFirebaseCloudFunctions() {
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://us-central1-<your-project-id>.cloudfunctions.net/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        FirebaseApi firebaseApi = retrofit.create(FirebaseApi.class);
        Call<String> call = firebaseApi.getShippingPrice();
        call.enqueue(new Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i(TAG, "onResponse: isSuccessful "+response.isSuccessful());
                Log.i(TAG, "onResponse: body: "+response.body());
                Log.i(TAG, "onResponse: errorBody: "+response.errorBody());
                try {
                    Log.i(TAG, "onResponse: error: "+response.errorBody().string());
                } catch (IOException e) {
                    Log.i(TAG, "onResponse: catherror: "+e.getMessage());

                }

            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.i(TAG, "onFailure: "+t.getMessage());
            }
        });
    }

日志如下所示:

onResponse: isSuccessful false
onResponse: body: null
onResponse: errorBody: okhttp3.ResponseBody@3e75b8d
onResponse: error: <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Error</title>
    </head>
    <body>
    <pre>Cannot POST /</pre>
    </body>
    </html>

我怎样才能让它工作?

我看过一些添加 CORS 的教程。即使我的应用连接到 firebase 并使用 firestore 和实时数据库,我真的需要 CORS 吗?

感谢任何帮助!

使用您当前的代码,POST 的正确路径是:

https://us-central1-<your-project-id>.cloudfunctions.net/shipping/shipping

这是因为您将函数导出为 shipping,但也只监听相对路径 /shipping

上的 POST 请求