【问题标题】:Send fcm message to specific topic via retrofit android (kotlin)通过改造 android (kotlin) 向特定主题发送 fcm 消息
【发布时间】:2021-04-09 00:04:04
【问题描述】:

我试图通过改造在 fcm 中发送特定主题的消息,我按照 fcm 中的说明进行操作,但我不断收到我的 http 请求的 404 代码,这就是我的代码:

常量文件:

class Constans {

companion object{
    const val BASE_URL = "https://fcm.googleapis.com"
    const val CONTENT_TYPE  ="application/json"
    const val SERVER_KEY ="myKey"
}

}

通知接口:

interface NotificationApi {

@Headers("Authorization: key=$SERVER_KEY", "Content-Type:${CONTENT_TYPE}")
@POST("fcm/send")
suspend fun postNotification(
    @Body message: Message
): Response<ResponseBody>

}

改造实例:

class RetrofitInstance {

companion object{
    private val retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }

    val api by lazy {
        retrofit.create(NotificationApi::class.java)
    }
}

}

消息类:

data class Message(
    var to:String,
    var data:Notification,
)

通知类:

data class Notification (
    val body:String="",
    val title:String=""
)

发送通知功能:

    private fun sendNotification(body:String,title:String)= CoroutineScope(Dispatchers.IO).launch {
    try {
        //orders is the topic name
        val message = Message("orders",Notification(body,title))
        val response = RetrofitInstance.api.postNotification(message)
        if (response.isSuccessful) {
            Log.e("msg1", response.message())
        } else {
            //here i get 404
            Log.e("msg", response.code().toString())
        }
    } catch (e: Exception) {
        Log.e("Error", e.message.toString())
    }

}

【问题讨论】:

    标签: android firebase kotlin firebase-cloud-messaging retrofit


    【解决方案1】:

    您是否尝试过像这样修改您的代码

        interface NotificationApi {
    
        @Headers("Authorization: key=$SERVER_KEY", "Content-Type:$CONTENT_TYPE")
        @POST("fcm/send")
        suspend fun postNotification(
          @Body message: Message
        ): Response<ResponseBody>
    

    【讨论】:

      【解决方案2】:

      对此我不确定,但是如果您将 Notification Api - @Headers 更改为会发生什么

      interface NotificationApi {
      
      @Headers("Authorization: Bearer $SERVER_KEY", "Content-Type:${CONTENT_TYPE}")
      @POST("fcm/send")
      suspend fun postNotification(
          @Body message: Message
      ): Response<ResponseBody>
      

      【讨论】:

      • 没有发生同样的错误,我尝试对另一个应用程序执行相同的步骤并将其链接到同一个 firebase 项目,它完美运行,这是我一生中遇到的最奇怪的错误。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-09-21
      • 2016-09-21
      • 2021-06-17
      • 2016-11-30
      • 2018-12-02
      • 1970-01-01
      相关资源
      最近更新 更多