使用VB.NET向android模拟器发送通知获取错误401
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用VB.NET向android模拟器发送通知获取错误401相关的知识,希望对你有一定的参考价值。
我正在编写VB.NET代码来向android Emulator发送通知。我可以成功从firebase控件发送测试消息。但是,当我尝试通过本地计算机中的VB.NET代码发送消息并收到错误“远程服务器返回错误:(401)未经授权”时,它失败了。
我试过看下面的链接:FCM (Firebase Cloud Messaging) Push Notification with Asp.Net并按照说明操作,但它仍然无法正常工作。
这是我的代码:
Imports System.Net
Imports Newtonsoft.Json
Public Class Notification
Public Sub SendNotification(ByVal deviceIDList As List(Of String), ByVal title As String, ByVal bodyMsg As String)
Dim fcmPath As String = "https://fcm.googleapis.com/fcm/send"
Dim serverKey As String = "AIzaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxoCAeI"
Dim senderID As String = "35xxxxxxx37"
Dim request As HttpWebRequest = CType(HttpWebRequest.Create(fcmPath), HttpWebRequest)
With request
.Method = "POST"
.ContentType = "application/json"
.Headers.Add(String.Format("Authorization: key={0}", serverKey))
.Headers.Add(String.Format("Sender: id={0}", senderID))
End With
Using streamWriter = New StreamWriter(request.GetRequestStream())
Dim webObject As New WebRequestFcmData
With webObject
.registration_ids = deviceIDList
.notification.title = title
.notification.body = bodyMsg
.notification.content_available = True
.notification.sound = "default"
.notification.priority = "high"
End With
Dim body = JsonConvert.SerializeObject(webObject)
With streamWriter
.Write(body)
.Flush()
.Close()
End With
End Using
Dim httpResponse = CType(request.GetResponse(), HttpWebResponse)
Using streamReader As New StreamReader(httpResponse.GetResponseStream)
Dim result = streamReader.ReadToEnd
End Using
End Sub
End Class
Public Class WebRequestFcmData
Public Property registration_ids As List(Of String)
Public Property notification As New NotificationData
End Class
Public Class NotificationData
Public Property body As String
Public Property content_available As Boolean
Public Property priority As String
Public Property title As String
Public Property sound As String
End Class
错误发生在该行:
Dim httpResponse = CType(request.GetResponse(), HttpWebResponse)
更新:我尝试从Postman应用程序发送Web请求,它也给出了相同的错误(401:Unauthorized),如下图所示:
答案
好。我使用不是实际服务器密钥的API密钥犯了一个愚蠢的错误。即使我已经读到我应该在项目设置中转到云消息传递选项卡,但我误解了我必须查看侧栏中的云消息传递选项卡,这是错误的。这是我找到服务器密钥的步骤:
起初,我尝试在侧边栏中的云消息传递选项卡中寻找服务器密钥,这是错误的位置。
以上是关于使用VB.NET向android模拟器发送通知获取错误401的主要内容,如果未能解决你的问题,请参考以下文章
为啥不获取 Android Firebase FCM 注册令牌?
通知未显示在 Android 设备上。 (Azure 通知中心)