我正在尝试使用 Firebase Cloud Messaging HTTP v1,但是当我在调用 openConnection() 后获得响应代码时,会返回“404”错误代码
URL url = new URL(FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
System.out.println("status:" + httpURLConnection.getResponseCode());
我检查了 URL 中的项目 ID,应该是 Firebase 控制台中的项目 ID(设置 --> 常规 --> 项目 ID)
Firebase 控制台:
https://fcm.googleapis.com/v1/projects/xxxxxxxxx/messages:send
错误的:
{"message":{"notification":{"title":"notification title","body":"message body"},"token":"123"}}
正确的:
{"message":{"notification":{"title":"notification title","body":"message body"},"token":"dwB0YqF......"}}
这里是示例代码
public static HttpURLConnection getHTTPConn() throws Exception{
URL url = new URL(FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String token = getAccessToken();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + token);
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
httpURLConnection.setDoOutput(true);
return httpURLConnection;
}
//The following code to retrieve the token with Google API Client Library <https://firebase.google.com/docs/cloud-messaging/auth-server>
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
public static void sendPushNotificationV1(){
String result = "";
try{
HttpURLConnection conn = getHTTPConn();
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(json.toString());
wr.flush();
BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
String output;
while ((output = br.readLine()) != null) {
System.out.println(output);
}
result = "SUCCESS";
} catch (Exception e) {
e.printStackTrace();
}
}
享受~
检查 JSON 消息格式是否正确并包含有效字段(例如,确保传入正确的数据类型)。请阅读底部的此链接,您有响应代码和问题。HTTP 连接服务器参考和响应代码
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句