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



我正在尝试使用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$1@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请求