Я пытаюсь получить доступ к FCM из моего серверного приложения. Проверил приведенный пример в здесь ! Но получаю ошибку:
java.io.IOException: Server returned HTTP response code: 400 for URL: https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1627)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:254)
at asd.MessagesClientFCMServer.sendMessageToFcm(MessagesClientFCMServer.java:66)
at asd.MessagesClientFCMServer.sendData(MessagesClientFCMServer.java:40)
at asd.MessagesClientFCMServer.main(MessagesClientFCMServer.java:37)
Я уже создал проект firebase под названием "unsaarmdm" и загрузил файл json, который содержит закрытый ключ. Также добавил клиентскую библиотеку Google API в мой проект.
Ниже приведен фрагмент кода:
private static String FCM_DEALS_ENDPOINT
= "https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send";
//https://fcm.googleapis.com/v1/projects/unsaarmdm/messages:send
public static void main(String args[]) {
MessagesClientFCMServer fcmClient = new MessagesClientFCMServer();
fcmClient.sendData();
}
private void sendData(){
sendMessageToFcm(getFcmMessageJSONData());
}
//Using HttpURLConnection it send http post request containing data to FCM server
private void sendMessageToFcm(String postData) {
try {
HttpURLConnection httpConn = getConnection();
DataOutputStream wr = new DataOutputStream(httpConn.getOutputStream());
wr.writeBytes(postData);
wr.flush();
wr.close();
BufferedReader in = new BufferedReader(
new InputStreamReader(httpConn.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
log.info(response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
private static String getAccessToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("C:/dev/Firebase_private_key/unsaarmdm-firebase-adminsdk.json"))
.createScoped(Arrays.asList(SCOPE));
googleCredential.refreshToken();
String token = googleCredential.getAccessToken();
return token;
}
//create HttpURLConnection setting Authorization token
//and Content-Type header
private HttpURLConnection getConnection() throws Exception {
URL url = new URL(FCM_DEALS_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
httpURLConnection.setDoOutput(true);
httpURLConnection.setUseCaches(false);
httpURLConnection.setRequestMethod("POST");
httpURLConnection.connect();
return httpURLConnection;
}