首页 > 解决方案 > 错误请求 [400],带有改造的 FCM 旧版 HTTP API

问题描述

网址 = https://fcm.googleapis.com/fcm/send

请求正文

{
"registration_ids": ["token 1","token 2"],
"priority": "high",
"notification": {
"title": "Divine Public School",
"body": "Test Message."
} }

标题

{
"Content-Type: application/json",
"Authorization: key=<myServerKey>"
}

从邮递员点击此网址时,我收到状态代码 200,甚至在客户端应用程序中收到通知。但是当我尝试在 android 中使用 retrofit 做同样的事情时,我得到状态 400 Bad Request。

安卓代码如下

interface NotificationService {
@Headers("Content-Type: application/json",
    "Authorization: key=<my server key>")
@POST("fcm/send")
fun sendNotification(@Body body: NotificationBody): Call<ResponseBody> }

数据类

data class NotificationBody(
@SerializedName("registration_ids")
var registration_ids : ArrayList<String>,
@SerializedName("priority")
var priority:String,
@SerializedName("notification")
var notification:Notification  )

data class Notification(
@SerializedName("title")
var title:String,
@SerializedName("body")
var body:String     )

改造电话

val generalRetrofit = Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create())
.baseUrl("https://fcm.googleapis.com/")
.build()!!

val service = generalRetrofit.create(NotificationService::class.java)
val data = NotificationBody(....)
val call = service.sendNotification(data)
call.enqueue(object : Callback<ResponseBody> {
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {}
override fun onResponse(call: Call<ResponseBody>,response: Response<ResponseBody>)                  
{
 Log.d("TAG", response.code().toString())
 })

NotificationBody 对象的日志输出

D/TAG: NotificationBody(registration_ids=[cxd-PHM-QOyLcnLcPozjKA:APA91bGIG-NDg-hSYMlTGWm-ZVaM0hR7Om77CaksvZ4bLDKM0gU_xYk9_Um1aOzPExGR40FeHAqQpkjt_7-HiG8SMPtF5HLrUjCrcD4Asq_ZcEv-Du5AcMthcYjaZjisduLkBPhgPH0b], priority=higher, notification=Notification(title=Divine Public Sc​​hool, body=Hello))

标签: androidfirebasefirebase-cloud-messagingretrofitretrofit2

解决方案


不是一个合适的解决方案,但在我现有的 Node 项目中做了一个端点。任何有此问题的人都可以使用它。网址https://pankaj-oil-api.herokuapp.com/notify

您需要在上面的 url 上发布这个对象。“registration_ids”是一个字符串数组,可以有最少 1 个和最多 1000 个令牌。

{
"registration_ids" : ["Client Token 1","Client Token 2"],
"serverKey": "<Your (Authorization) Server Key Here>",
"title": "<Enter your Notification Title here >",
"msg":"<Enter your Notification Message here >"
}

代码

这只是一个临时解决方案。仍在寻找解决方案。


推荐阅读