在Java中从服务器发送到安卓设备的推送通知
2022-09-02 13:04:54
我正在与新的FCM作斗争...我以前使用过FCM,现在我正在尝试FCM...
我正在尝试将我的应用程序服务器的推送通知发送到安卓设备。
我想使用标准的Java包,尽量不要使用其他的,如Vert.x,apache的httpClient等...
这是我的代码:
public void sendNotification(String messageBody)
{
try
{
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
String apiKey = "AI...wE";
String credentials = "key=" + apiKey;
//String basicAuth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());
String basicAuth = "Basic " + new String(Base64.encodeBase64(credentials.getBytes()));
conn.setRequestProperty ("Authorization", basicAuth);
String notfnStr = "{\"body\": \"this is my body\", \"title\": \"this is my title\"}";
String dataStr = "{\"key1\": \"value1\", \"key2\": \"value2\"}";
String bodyStr = "{\"priority\": \"high\", \"to\": \"dFC8GW0N1Q8:APA91bHePPmC7QVV16LGnR6rqxwreHSv1GgawijZ_dZL9T70ZkiXIV8TW_ymAWkvFfXRiWJmtR_UGBXBv2iV2UhS8M-Tndw8sf8ZW6zIqfaiiVJao3G5HFbhqgA18ukNNtW_J7JaWkz8\", " +
"\"notification\": " + notfnStr + ", \"data\": " + dataStr + "}";
System.out.println("### input: " + bodyStr);
OutputStream os = conn.getOutputStream();
os.write(bodyStr.getBytes());
os.flush();
if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
System.out.println(output);
}
conn.disconnect();
}
catch (Exception e)
{
e.printStackTrace();
}
}
我得到的响应代码是401,这意味着未经授权...我猜凭据的格式是错误的...
json字符串是有效的json格式,所以我懒得使用JSONObject。
对于字符串凭据,我尝试了“键:”+apiKey;但仍然得到了相同的结果。
apiKey String是从我从Google的Firebase控制台下载的google-services.json复制的。
谷歌没有给出一个很好的例子...只是给了我这个:https://firebase.google.com/docs/cloud-messaging/downstream
如果有人知道如何做,请回复。谢谢!!