gpt4 book ai didi

java - 如何通过java服务器使用FCM向android设备发送推送通知?

转载 作者:行者123 更新时间:2023-12-01 09:34:16 25 4
gpt4 key购买 nike

我已经编写了这段代码,用于通过java服务器代码使用fcm发送通知。但它抛出异常服务器返回 HTTP 响应代码:500 对于 URL:https://fcm.googleapis.com/fcm/send

public static void pushFCMNotification(String userDeviceIdKey) throws     Exception{

String authKey = AUTH_KEY_FCM; // You FCM AUTH key
String FMCurl = API_URL_FCM;

URL url = new URL(FMCurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);

conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization","key="+authKey);
conn.setRequestProperty("Content-Type","application/json");

JSONObject json = new JSONObject();
json.put("to",userDeviceIdKey.trim());
JSONObject info = new JSONObject();
info.put("title", "Notificatoin Title"); // Notification title
info.put("body", "Hello Test notification"); // Notification body
json.put("notification", info);

OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
wr.close();

int responseCode = conn.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + json);
System.out.println("Response Code : " + responseCode);

BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();

while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();


/*OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
conn.getInputStream();*/
}

最佳答案

根据官方文档:

Errors in the 500-599 range (such as 500 or 503) indicate that there was an internal error in the FCM connection server while trying to process the request, or that the server is temporarily unavailable (for example, because of timeouts). Sender must retry later, honoring any Retry-After header included in the response. Application servers must implement exponential back-off.

来源:https://firebase.google.com/docs/cloud-messaging/http-server-ref#interpret-downstream

但是,请确保 JSON 请求的格式正确。尝试使用 json.toString() 更新您的问题,并使用 Checking the validity of a server key 中描述的过程检查您的 API key 是否仍然有效。

关于java - 如何通过java服务器使用FCM向android设备发送推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39140045/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com