我尝试使用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());
我检查了网址中的项目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();
}
}
享受〜