首页 > 解决方案 > 使用 volley 通过 FCM REST API 发送 POST 请求时出现身份验证错误

问题描述

我正在使用端点https://fcm.googleapis.com/v1/projects/{PROJECT_NAME}/messages:send向 Firebase 云消息传递服务器发送 POST 请求,以便向我的应用发送通知。问题是我收到错误 401,身份验证错误。我已经阅读了他们的文档https://firebase.google.com/docs/reference/fcm/rest/v1/projects.messages/send?apix=true很多次,我似乎无法理解为什么我会得到这个错误。我尝试在页面上使用 Google API Explorer 测试端点,它工作正常。通知已发送到我的应用程序。但是,在我的代码中使用 volley 发送相同的 POST 请求失败,并在 JSON 中出现以下错误:

{
  "error": {
    "code": 401,
    "message": "Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
    "status": "UNAUTHENTICATED"
  }
}

这是我所做的:

val FCM_POST = "https://fcm.googleapis.com/v1/projects/${Constants.PROJECT_NAME}/messages:send"

val map = mapOf("message" to
               mapOf("notification" to
                   mapOf("title" to "test title",
                          "body" to "test body")),
               "topic" to "testTopic")

    val request = object : JsonObjectRequest(
            Method.POST,
            FCM_POST,
            JSONObject(map), {
        showDialog.log(TAG, "sendMedicalTipsNotification response: $it")
    }, {
        val networkResponse = it.networkResponse
        if (networkResponse?.data != null) {
            val jsonError = String(networkResponse.data)
            try {
                val jsonObject = JSONObject(jsonError)
                showDialog.log(TAG, "sendMedicalTipsNotification error: $jsonObject")
            } catch (e: JSONException) {
                showDialog.log(TAG, "sendMedicalTipsNotification error: $e")
            }
        }
    }) {
        override fun getHeaders(): MutableMap<String, String> {
            return mutableMapOf("Authorization" to "Bearer ${Constants.MY_PROJECT_CLOUD_CONSOLE_CLIENT_ID}",
                    "Content-Type" to "application/json")
        }
    }

    Volley.newRequestQueue(ctx).add(request)
}

如您所见,我正在请求标头中发送我的 CLIENT_ID 和内容类型。我真的不知道为什么我会收到这个错误

标签: androidkotlinfirebase-cloud-messaginggoogle-cloud-console

解决方案


推荐阅读