使用Firebase REST API发送批处理消息失败。

问题描述 投票:0回答:1

我正在试验使用REST API在Firebase Cloud Messaging中发送批量消息。我用C#编写了一个多部分的HTTP请求。

using var request = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/batch");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "xxx");
request.Content = new StringContent(multicast);
request.Content.Headers.Remove("Content-Type");
request.Content.Headers.TryAddWithoutValidation("Content-Type", "multipart/mixed; boundary=--subrequest_boundary");
var response = await FcmHttpClient.SendAsync(request);

字符串的值是 multicast 上面的字段是一个HTTP内容,类似于在 火库文件:

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
Authorization: Bearer xxx

POST /v1/projects/myproject/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "topic":"global",
     "notification":{
       "title":"FCM Message",
       "body":"This is an FCM notification message to device 0!"
     }
  }
}

--subrequest_boundary
Content-Type: application/http
Content-Transfer-Encoding: binary
Authorization: Bearer xxx

POST /v1/projects/myproject/messages:send
Content-Type: application/json
accept: application/json

{
  "message":{
     "topic":"readers-club",
     "notification":{
       "title":"Price drop",
       "body":"2% off all books"
     }
  }
}

--subrequest_boundary--

Firebase服务器返回Bad Request-400的错误信息。"Failed to parse batch request, error: 0 items. Received batch body: --subrequest_boundary--" 这表明Firebase直接处理了带有终止符的内容。--subrequest_boundary--.

问题的原因可能是什么?

c# firebase-cloud-messaging dotnet-httpclient
1个回答
0
投票

恶魔就在构建的细节中。Content. 你不能简单地创建一个与有效载荷匹配的字符串,因为其中的某些部分,如头和边界,从技术上讲,并不被 HttpClient 栈。

如果你真的需要用一个原始的 HttpClient,看一看 Google APIs .NET客户端如何构建并发送批量请求?. 但我猜想,一旦你意识到这是多么的繁琐,你就会得出结论,你最好使用更高级别的SDK,如 火库管理网在你链接到的同一份文档中也提到了,它利用了Google的.NET客户端。

© www.soinside.com 2019 - 2024. All rights reserved.