我试图通过改进在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"
}
}
通知Api:
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())
}
}
你有没有试着像这个一样修改你的代码
interface NotificationApi {
@Headers("Authorization: key=$SERVER_KEY", "Content-Type:$CONTENT_TYPE")
@POST("fcm/send")
suspend fun postNotification(
@Body message: Message
): Response<ResponseBody>
我不确定,但如果将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>