我这样做了:
public class PushNotifictionHelper {
public final static String AUTH_KEY_FCM = "AIzaSyD63pfTvnwhe9WVuIe.........";
public final static String API_URL_FCM = "https://fcm.googleapis.com/fcm/send";
public static String sendPushNotification(String deviceToken)
throws IOException, JSONException {
String result = "";
URL url = new URL(API_URL_FCM);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", "key=" + AUTH_KEY_FCM);
conn.setRequestProperty("Content-Type", "application/json");
JSONObject json = new JSONObject();
json.put("to", deviceToken.trim());
JSONObject info = new JSONObject();
info.put("title", "notification title"); // Notification title
info.put("body", "message body"); // Notification
// body
json.put("notification", info);
try {
OutputStreamWriter wr = new OutputStreamWriter(
conn.getOutputStream());
wr.write(json.toString());
wr.flush();
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);
}
result = "OK";
} catch (Exception e) {
e.printStackTrace();
result = "BAD";
}
System.out.println("GCM Notification is sent successfully");
return result;
}
public static void main(String [] args){
try {
PushNotifictionHelper.sendPushNotification("ep51x3Ckmig:APA91bG4PdoJC7zGlV0JPmCA49jmqJCkeSPH1QzF9byxdH1nRlFOVyAi9ppO2ygoSpp8s44o1oGO8n-HCJDB_oZAZ6WCwFD2a9yAFmKIpKhmPXakeLf-ktqPnzwf-GFziv7_nMdVPIci");
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
当我在控制台中运行它时,我看到
java.io.IOException: Server returned HTTP response code: 401 for URL: https://fcm.googleapis.com/fcm/send
我从网上获得的 AUTH_KEY_FCM:
Klucz interfejsu Web API AIzaSyD63pfTvnwhe9WVuIe.........
401 错误是指身份验证错误。从文档:
用于发送邮件的发件人帐户无法通过身份验证。可能的原因有:
- HTTP 请求中缺少授权标头或使用无效的语法。
- 作为密钥发送的项目编号无效。
- 密钥有效但禁用了 FCM 服务。
- 请求源自未在服务器密钥 IP 中列入白名单的服务器。
检查您在 Authentication 标头内发送的令牌是否是与您的项目关联的正确服务器密钥。有关详细信息,请参阅检查服务器密钥的有效性。
使用 FCM 时,您应该始终使用Firebase 控制台的Cloud Messaging选项卡中显示的服务器密钥(而不是 Web API 密钥)。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句